Skip to content

Instantly share code, notes, and snippets.

@niraj-shah
Last active February 19, 2016 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niraj-shah/c6c0ed312ed52e5d78b7 to your computer and use it in GitHub Desktop.
Save niraj-shah/c6c0ed312ed52e5d78b7 to your computer and use it in GitHub Desktop.
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