首页 > 解决方案 > 使用 Fortify Laravel 8 使用电子邮件或用户名登录

问题描述

我正在尝试允许用户使用电子邮件或用户名及其密码登录。

我在 FortifyServiceProvider.php 的 boot() 中添加了以下代码:

Fortify::authenticateUsing(function (Request $request) {
        $user = User::where('email', $request->email)
            ->orWhere('username', $request->username)
            ->first();

        if ($user &&
            Hash::check($request->password, $user->password)) {
            return $user;
        }
    });

但是现在当用户尝试通过输入他们的用户名而不是电子邮件来登录时,他们会收到以下错误消息:

These credentials do not match our records.

标签: phplaravellaravel-8laravel-authenticationlaravel-fortify

解决方案


我忘记更改以下行:

->orWhere('username', $request->username)

到:

->orWhere('username', $request->email)

因为我的登录表单中只有一个字段可以保存电子邮件或用户名。此字段的名称是“电子邮件”。


推荐阅读