Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Laravel 5.x Custom Validation Rules
// Remember to include the required classes, e.g. Hash, Validator, Redirect, User model
// define validation rules, 'password' will be our custom rule
$rules = [
'current_password' => 'required|password',
'password' => 'required|confirmed|min:6',
];
// custom rule for 'password'
Validator::extend('password', function( $attribute, $value, $parameters ) {
// compare the entered password with what the database has, e.g. validates the current password
return Hash::check( $value, Auth::user()->password );
});
// custom message if validation for password fails
$messages = [ 'password' => 'Your current password does not match our records.' ];
// validate input with rules, adding in custom messages
$validation = Validator::make( Input::all(), $rules, $messages );
// if validation fails, redirect back to previous page
if ( $validation->fails() ) {
return Redirect::back()->withInput()->withErrors( $validation->messages() );
}
// Update the password
User::find( Auth::user()->id )->update( [
'password' => Hash::make( Input::get('password') )
] );
// redirect with success message
return Redirect::back()->with( ['message' => 'Your password was updated successfully.'] );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.