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

标签 php laravel laravel-8 laravel-livewire laravel-jetstream

我正在寻找一种解决方案,将标准 Jetstream 身份验证更改为使用用户名或电子邮件进行身份验证。这意味着在注册帐户期间,您输入电子邮件或用户名(始终需要用户名)。在登录表单中,您可以输入用户名或电子邮件作为您的凭据。我还更改了个人资料设置以更新用户名。

我的实际问题是

  1. 仅使用用户名注册时,出现电子邮件字段为空的错误 registration error

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

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

<强>1。更改config/fortify.php

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

2.在启动方法内的 app/Providers/FortifyServiceProvider.php 添加身份验证代码

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> 

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

4.将用户名添加到用户模型

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('用户名', $request->email)->first();

检查Customizing User Authentication在 Laravel Fortify 上。

关于php - 使用 jetstream 在 laravel 8 中进行身份验证 - 用户名或电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65003553/

相关文章:

php - Symfony2+学说 : How to convert iso8859-1 to utf-8 and viceversa?

php - 如何结合 Prestashop (PHP) 和 DjangoCMS (Python)

php - 当重写引擎删除 .php 和 .html 时,无法访问文件夹中的索引

php - 在 ColdFusion 中验证来自 Microsoft Teams 自定义机器人的 HMAC

php - Eloquent:根据关系过滤记录

php - Laravel 如何返回并在 HTML 中显示 SQL 错误?

php - Laravel 8 中的自定义 DatabaseSessionHandler

php - Laravel Framework 中的更新正在返回一条新记录

php - Laravel 5 - ORM has() 关系(反向 - notHas)

Laravel 按 Eloquent 关系分组