4

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

1
  • You can use like: \Session::flash('error', 'Wrong password or this account not approved yet'); return redirect()->back()->withInput()->withErrors($errors); And then print the session message in the blade file! Commented Aug 3, 2017 at 6:42

3 Answers 3

11

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;
Sign up to request clarification or add additional context in comments.

2 Comments

hmmm... interesting, but where should i put message 'Wrong password' ?
When you validate Auth::attempt, if it fails you can add a message doing this: $validator->getMessageBag()->add('password', 'Wrong password'); And return withErrors($validator) on your redirect()->back()
1

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);
    }

    

2 Comments

return redirect(route('login'))->with('error', 'Please enter correct login credentials' ); will help you. Thanks.
in blade view file @if (session('error')) <div class="alert alert-danger alert-dismissible show"> {{ session('error') }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> @endif
0

You can use like this:

return Redirect::back()->withInput(Input::all());

If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.

Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:

return redirect()->to($this->getRedirectUrl())
                    ->withInput($request->input())
                    ->withErrors($errors, $this->errorBag());

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()
            ->withErrors(
                [
                    'password' => 'Wrong Password',
                ],
                [
                    'approve' => 'Account not approved',
                ],
            );
}

5 Comments

Sorry maybe u miss understand me, i want to show error when password is incorrect
Try to use ` return redirect::back()->withInput()->withFlashMessage('Wrong password or this account not approved yet.');`
I want to separate: If the password does not match show: Wrong Password. And if account not approved show: Account not approved.
@DmitryMalys For that, you can check separate if conditions and return separate flash messages!
Try this: return Redirect::back() ->withInput() ->withErrors( [ 'password' => 'Wrong Password', ], [ 'approve' => 'Account not approved', ], );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.