且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Laravel 8中使用用户名和密码进行身份验证时出现问题

更新时间:2022-05-07 21:36:47

适用于Laravel-Jetstream的解决方案

您可以按照以下步骤使用用户名或电子邮件进行身份验证.

You can authenticate using username or email following this steps.

1..确认登录输入字段名称(名称为 identity )

1. Confirm login input field name (Let name is identity)

2.更改 config/fortify.php

'username' => 'email' to  'username' => 'identity'

3..在 boot 方法内的 app/Providers/FortifyServiceProvider.php 文件中添加了以下身份验证代码

3. Added following authentication code in your app/Providers/FortifyServiceProvider.php file 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;
            }
        });

[注意]请使用这些类

[Note] Please use those classes

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

#用于注册用户名

1..在 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>

2..在用户模型 $ fillable 数组列表中添加 username .

2. Add username in User model $fillable array list.

3.最后更改 app/Actions/Fortify/CreateNewUser.php 文件

Validator::make($input, [
            ..........
            'username' => ['required', 'string', 'max:255', 'unique:users'],
            .........
        ])->validate();

        return User::create([
           .......
            'username' => $input['username'],
            .....
        ]);
    }

让我们享受认证.