首页 > 解决方案 > 如何使 RegisterController 的 create 方法在 Laravel 5 中生成 Profile 条目

问题描述

用户的详细信息存储在两个单独的表UserProfile.

我正在使用 Laravel 的内置身份验证,即:

php artisan make:auth

一旦用户注册,我希望除了创建一个User条目之外,还会创建一个随附的Profile条目(所有值都设置为 null)并User通过 FK 链接到该条目。

然后用户被重定向到一个页面,他可以在其中填写Profile详细信息。

// create_users_table.php

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('username')->unique();
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

// create_profiles_table.php

Schema::create('profiles', function (Blueprint $table) {
    $table->integer('user_id')->unsigned()->nullable();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->date('date_of_birth');
    $table->string('city');
});

我猜想在调用's函数Profile时必须实例化并保存相应的对象。RegisterControllercreate

protected function create(array $data)
{
    return User::create([
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}

在哪里创建和保存相应的 Profile 对象?

这个问题已经被问过了。一位成员建议对 进行更改app/Services/Registrar.php,但 Laravel 5.4.0 似乎没有上述文件。有谁知道他所指的等效代码可以在 5.4.0 中找到吗?

标签: phplaravel

解决方案


首先,为了让事情更容易,让我们profile()在用户模型中定义关系。所以,在 中App\User,你会有这样的东西。

public function profile()
{
    return $this->hasOne(Profile::class); 
}

我假设用户只有一个配置文件。如果他们有很多,请相应地更新关系。

然后,在 中App\Http\Controllers\Auth\RegisterController,您将像这样覆盖该create()方法:

protected function create(array $data)
{
    $user = User::create([
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

    // Creates the user profile
    $profile = Profile::create([
        //
    ]); 

    // Associates the relationship
    $user->profile()->save($profile); 

    // This, of course, assumes you have 
    // the above relationship defined in your user model.

    return $user; 
}

或者,您可以挂钩到用户的模型事件。在你的App\User类的boot()方法中,你会有这样的东西。

public static function boot()
{
    parent::boot(); 

    static::created(function ($user)) {
        $profile = Profile::create([
            //
        ]); 

        $user->profile()->save($profile); 
    }); 
}

现在,每次创建用户时,都会关联相应的配置文件。


推荐阅读