Laravel "Wrong password" error message

Viewed 19843

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

3 Answers

Without writing a new custom login method we can easily handle a custom wrong password message with the Auth default login process.

Open LoginController from the location: app/Http/Controllers/Auth/

Include the Request class if not exit on top of the controller

use Illuminate\Http\Request;

Finally add below line of codes at the very bottom of your LoginController to process the response error with custom message



    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        $errors = [$this->username() => trans('auth.failed')];
    
        // Load user from database
        $user = \App\User::where($this->username(), $request->{$this->username()})->first();
    
        if ($user && !\Hash::check($request->password, $user->password)) {
            $errors = ['password' => 'Wrong password'];
        }
    
        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }
    
        return redirect()->back()
            ->withInput($request->only($this->username(), 'remember'))
            ->withErrors($errors);
    }

    

Related