Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel "Wrong password" error message

I'm creating a login function in Laravel 5.4 and I want to show error message in the view when the password is incorrect. Also I have a custom message for account approval so it makes things a bit difficult for me. Meanwhile I put those messages together but is not very user-friendly. How can I separate them?

This is my controller:

public function login(Request $request)
{
    // validate the form data
    $this->validate($request, [
        'email' => 'required|email|exists:users,email',
        'password' => 'required|min:6'
    ]);

    // attempt to log
    if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {

        // if successful -> redirect forward
        return redirect()->intended(route('user.overview'));
    }

    // if unsuccessful -> redirect back
    return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
        'approve' => 'Wrong password or this account not approved yet.',
    ]);
}

As result i want to replace Wrong password or this account not approved yet with two separate messages:

If password is wrong to show: Password is wrong If account not approved show: This account not approved yet

like image 931
Dmitry Malys Avatar asked Jan 03 '23 15:01

Dmitry Malys


1 Answers

You can pass custom error messages for each validation rule, you can do this:

    public function login(Request $request)
    {
        //Error messages
        $messages = [
            "email.required" => "Email is required",
            "email.email" => "Email is not valid",
            "email.exists" => "Email doesn't exists",
            "password.required" => "Password is required",
            "password.min" => "Password must be at least 6 characters"
        ];
        
        // validate the form data
        $validator = Validator::make($request->all(), [
                'email' => 'required|email|exists:users,email',
                'password' => 'required|min:6'
            ], $messages);
    
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        } else {
            // attempt to log
            if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
                // if successful -> redirect forward
                return redirect()->intended(route('user.overview'));
            }
    
            // if unsuccessful -> redirect back
            return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
                'approve' => 'Wrong password or this account not approved yet.',
            ]);
        }
    }

Before this, you have to include Validator class:

use Illuminate\Support\Facades\Validator;
like image 65
Diego Blaker Avatar answered Jan 12 '23 07:01

Diego Blaker