使用 jetstream 在 laravel 8 中进行身份验证 - 用户名或电子邮件

authenticating in laravel 8 with jetstream - username or email

我正在寻找将标准 Jetstream Auth 更改为使用用户名或电子邮件进行 Auth 的解决方案。这意味着您在注册帐户时输入电子邮件或用户名(始终需要用户名)。在登录表单中,您可以输入用户名或电子邮件作为您的凭据。我还更改了配置文件设置以更新用户名。

我的实际问题是

  1. 在仅使用用户名注册期间,我收到空电子邮件字段的错误 registration error

  2. 登录时,用户名将不是正确的凭据

我已经更改了与 post Problem authenticating with username and password in Laravel 8 类似的所有内容,但它不起作用。

1. config/fortify.php

的变化
'username' => 'email' to 'username' => 'identity'

2.added 验证码到 app/Providers/FortifyServiceProvider.php inside boot method

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

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

还添加了类

use Laravel\Fortify\Http\Requests\LoginRequest;
use App\Models\User;

3。注册时添加的用户名register.blade.php

下方添加输入字段
<div class="mt-4">
            <x-jet-label for="username" value="{{ __('User Name') }}" />
            <x-jet-input id="username" class="block mt-1 w-full" type="text" name="username" :value="old('username')" required autofocus autocomplete="username" />
</div> 

并从电子邮件表单字段中删除了 required

4.add 用户模型的用户名

protected $fillable = [
    'name',
    'email',
    'password',
    'username',
];

app/Actions/Fortify/CreateNewUser.php

的变化
Validator::make($input, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['string', 'email', 'max:255', 'unique:users'],
        'username' => ['required', 'string', 'max:255', 'unique:users'],
        'password' => $this->passwordRules(),
    ])->validate();

    return User::create([
        'name' => $input['name'],
        'email' => $input['email'],
        'username' => $input['username'],
        'password' => Hash::make($input['password']),
    ]);

5.将用户名字段添加到数据库

Schema::table('users', function (Blueprint $table) {
        $table->string('username')->nullable();
    });

在您的第一种情况下,用户名是必需的,但电子邮件是可选的,您需要将 nullable 添加到您的验证属性中。请查看 optional fields.

上的文档

对于您的第二个用例,login.blade.php 默认输入标签是 name="email"。这意味着你的情况将是 $user = User::where('email', $request->email)->orWhere('username', $request->email)->first();

在 Laravel Fortify 上检查 Customizing User Authentication