I have a basic form set up to allow a user to change their email address, and I'm doing the following validation on it before I change the email:
// Set up the form validation $validator = Validator::make( Input::all(), array( 'email' => 'email|unique:users', 'password' => 'required' ) ); // If validation fails, redirect to the settings page and send the errors if ($validator->fails()) { return Redirect::route('settings')->withErrors($validator)->withInput(); }
This works fine, however after this basic validation I'd like to check if the user supplied a correct password. To do so, I'm doing the following with Laravel's basic authentication library:
// Find the user and validate their password $user = Auth::user(); if (!Auth::validate(array('username' => $user->username, 'password' => Input::get('password')))) { die("failed to authenticate"); }
Rather than handling the logic to tell the user their password is incorrect myself, I'd rather just add a form error to the password
input so it shows up just like regular form validation. Something like so:
if (!Auth::validate(array('username' => $user->username, 'password' => Input::get('password')))) { $validator->addError('password', 'That password is incorrect.'); return Redirect::route('settings')->withErrors($validator)->withInput(); }
That way, the incorrect password error will show next to my password input and look like proper form validation.
How can I do this?
After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user.
Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.
Customizing Validation Rules Using Laravel. Share. While you are working with user input and forms, validating the common fields and extracting the exact validation rules makes the code easier to maintain and read. You can make the code powerful by using the Laravel custom validation rule with parameters.
See Darren Craig's answer.
One way to implement it though.
// inside if(Auth::validate) if(User::where('email', $email)->first()) { $validator->getMessageBag()->add('password', 'Password wrong'); } else { $validator->getMessageBag()->add('email', 'Email not found'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With