Wai*_*ein 10 laravel laravel-authentication laravel-8 laravel-jetstream
我开始使用 Laravel 8 构建一个 Web 应用程序。我注意到 Laravel 8 中的很多事情都发生了变化,包括身份验证。现在,我正在尝试使用 Jetstream 进行身份验证。
我已运行以下命令将其集成到应用程序中。
composer require laravel/jetstream
php artisan jetstream:install inertia
npm install && npm run dev
Run Code Online (Sandbox Code Playgroud)
当我去/register路线时,我可以看到包含姓名、电子邮件、密码和密码确认字段的注册表。我想要做的是我想添加另一个名为“公司”的字段,我想对其应用自定义验证规则。
我在 Jetstream 文档中发现,我可以在 JetstreamServiceProvider 类的引导方法中自定义身份验证过程,如下所示。
Fortify::authenticateUsing(function (Request $request) {
});
Run Code Online (Sandbox Code Playgroud)
但不适用于注册。如何自定义注册过程添加新字段和应用自定义验证规则?
Ali*_*Ali 15
首先,您应该company使用 中找到的迁移将该字段添加到用户表中database\migrations\2014_10_12_000000_create_users_table.php。
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('company');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
}
Run Code Online (Sandbox Code Playgroud)
然后运行此命令php artisan migrate:fresh来迁移您的新用户表。
然后将该字段添加到User模型中的可填充数组中,\app\Models\User.php如下所示:
protected $fillable = [
'name',
'company',
'email',
'password',
];
Run Code Online (Sandbox Code Playgroud)
现在您可以在下方找到注册视图,resources\views\auth\register.blade.php然后您可以复制一个输入块以将其用于该'company'字段。
然后你可以在这个类中进行验证: app\Actions\Fortify\CreateNewUser.php
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'company' => ['required', 'string', 'max:255'],
'password' => $this->passwordRules(),
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'company' => $input['company'],
'password' => Hash::make($input['password']),
]);
}
Run Code Online (Sandbox Code Playgroud)
然后,你准备好了。
| 归档时间: |
|
| 查看次数: |
5876 次 |
| 最近记录: |