在Laravel 8中使用用户名和密码进行身份验证时出现问题 [英] Problem authenticating with username and password in Laravel 8

查看:54
本文介绍了在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'],
            .....
        ]);
    }

让我们享受认证.

这篇关于在Laravel 8中使用用户名和密码进行身份验证时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆