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

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

问题描述:

我最近开始使用Laravel 8,我试图同时使用用户名和电子邮件登录,但我不知道该怎么做.在Laravel 7中,我可以使用...

I recently started using Laravel 8 and I am trying to log in using username and email together but I do not know how to do this. In Laravel 7 I could use...

protected function credentials(Request $request)
{
    $field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL)
        ? $this->username()
        : 'username';
    
    return [
        $field => $request->get($this->username()),
        'password' => $request->password,
    ];
}

由于 Auth 文件夹中不再有 LoginController ,我该如何在Laravel 8中使用用户名和密码登录?

How can I log in using both username and password in Laravel 8 since there is no LoginController inside the Auth folder anymore?

适用于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'],
            .....
        ]);
    }

让我们享受认证.