简体   繁体   中英

how to handle laravel login errors, username different from password

I'm using Laravel 5.4 and I want to handle failed login errors message. But I want make it a little more custom. I want to show special errors like (username not found) or (password is wrong).

What can I do? (I did it and it's working, check my new failed login method, is this correct and standard?)

Failed login method:

protected function sendFailedLoginResponse(Request $request)
{
    $errors = [$this->username() => trans('auth.failed')];

    if ($request->expectsJson()) {
        return response()->json($errors, 422);
    }

    return redirect()->back()
    ->withInput($request->only($this->username(), 'remember'))
    ->withErrors($errors);
}

in my blade:

@if ($errors->first('phone'))
    <ul>
        @foreach($errors->all() as $error)
            <li>{{ $errors->first('phone') }}</li>
        @endforeach
    </ul>
@endif

my new failed method:

if (!User::where('phone', $request->phone)->first()){
    return redirect()->back()
        ->withInput($request->only($this->username(), 'remember'))
        ->withErrors([
            $this->username() => 'user not found',
        ]);
}


if (!User::where('phone', $request->phone)->where('password', bcrypt($request->password))->first()){
    return redirect()->back()
        ->withInput($request->only($this->username(), 'remember'))
        ->withErrors([
            'password' => 'password is incorrect',
        ]);
}

您可以在资源> lang> zh> passwords.php或auth.php文件中更改默认身份验证消息。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM