John Dorean John Dorean - 1 year ago 103
PHP Question

Adding custom validation errors to Laravel form

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(
'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
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?

Answer Source

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');
    $validator->getMessageBag()->add('email', 'Email not found');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download