thesimons's avatar

Alternative way to achieve this kind of validation

Hello,

don't kill me please. I tried the Laravel "validation" style but I'm unable to get the same result for the following (dirty) code.

Basically I want to flash one error at time. Could you please suggest a cleaner approach?

Thanks Simon

0 likes
5 replies
thesimons's avatar

I have redacted the guard with a generic "foo" for privacy.

tykus's avatar

The framework's validator will be more robust; you can bail or stopOnFirstFailure on the first failure on any attribute, you can validate the current_password for a given guard. You can specify your custom error messages, and even return only the first failure if that's what you want (although this is horrible UX in my opinion - if the user makes multiple mistakes, then let them know to fix all of them:

$validator = Validator::make($request->all(), [
    'current_password' => ['bail', 'required', 'current_password:foo'],
    'new_password' => ['bail', 'required'],
    'new_password_verify' => ['bail', 'required'],
], [
    'current_password.required' => 'lang.profile.settings.preferences.password.current_password.error.required',
    'new_password.required' => 'lang.profile.settings.preferences.password.new_password.error.required',
    'new_password_verify.required' => 'lang.profile.settings.preferences.password.new_password_verify.error.required',
]);
if ($validator->stopOnFirstFailure()->fails()) {
    return back()
        ->withInput()
        ->withErrors()
        ->with('hasLinkBack', true);
}

// Update password
auth('foo')->user()->update(['password' => Hash::make($request->new_password)]);

return redirect()
    ->route('my.profile.settings.preferences.password.edit')
    ->with('success', 'lang.profile.settings.preferences.password.updated_successfully');
1 like
martinbean's avatar

@thesimons What is the motivation for only showing one error at a time? Because as @tykus says, if there are multiple errors, and I resolve one, re-submit, and just get presenting with a different error, there’s only so many times I’m going to go through that process before I go, “F— this” and leave your site and never return.

1 like
thesimons's avatar

That's a good point! However this is the logic for panel into the "private area".

Many errors would "redundant". In example if new_password is missing, I just need to have an error saying "password missing". I don't need "password missing" and "passwords don't match".

Tray2's avatar

You won't as long as you mind the order you add the validations.

Please or to participate in this conversation.