11

我开始使用 Laravel 8 构建一个 Web 应用程序。我注意到 Laravel 8 中发生了很多变化,包括身份验证。现在,我正在尝试使用 Jetstream 进行身份验证。

我已运行以下命令将其集成到应用程序中。

composer require laravel/jetstream
php artisan jetstream:install inertia
npm install && npm run dev

当我去/register路线时,我可以看到带有姓名、电子邮件、密码和密码确认字段的注册表单。我想做的是我想添加另一个名为“公司”的字段,并且我想对其应用自定义验证规则。

我在 Jetstream 文档中发现,我可以在 JetstreamServiceProvider 类的引导方法中自定义身份验证过程,如下所示。

Fortify::authenticateUsing(function (Request $request) {
            
        });

但不适用于注册。如何自定义注册过程添加新字段并应用自定义验证规则?

4

2 回答 2

18

首先,您应该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();
        });
    }

然后运行此命令php artisan migrate:fresh以迁移您的新用户表。

然后将该字段添加到User模型中的可填充数组中,\app\Models\User.php如下所示:

protected $fillable = [
    'name',
    'company',
    'email',
    'password',
];

现在您可以在下面找到注册视图,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']),
        ]);
    }

然后,你准备好了。

于 2020-10-11T01:59:38.853 回答
4

@Ali Ali 的答案是正确的,但是如果对于那些使用 Inertia 的人来说,还有一个额外的步骤。您需要打开resources/js/Pages/Auth/Register.vue所需的字段并将其添加到表单中。此外,向下滚动到文件底部并将字段名称添加到this.$inertia.form输入参数对象文字。例如,如果所需的附加字段名称是company您将像这样添加它:

data() {
  return {
    form: this.$inertia.form({
      name: '',
      company: '', // <- New line here
      email: '',
      password: '',
      password_confirmation: '',
      terms: false,
    })
  }
},
于 2021-01-29T16:09:04.067 回答