在寄存器Laravel

时间:2019-04-29 22:14:20

标签: laravel

用户注册后,如何将某些默认用户设置保存在我拥有的表user_settings中?我有2个模型的hasOne和belongsTo关系设置。我在寄存器控制器中尝试过类似的操作,但是出现了错误。

    protected function create(array $data)
{

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);

    Return Usersetting::create([
        'user_id' => $user->id,
        'user_name' => 'u'.$user->id,
        'profile_name' => $user->name,
        'user_email' => $user->email,
        'user_private account' => 0,
        'user_fans_counter' => 1,
        'new_subscriber_alert' => 1,
        'new_tip_alert' => 1,
        'new_private_message_alert' => 1,
        'new_referral_alert' => 1,
    ]);
}

1 个答案:

答案 0 :(得分:1)

您可以删除第二部分,并在registered中添加一个RegisterController方法。如果您正确设置了关系,则可以如下添加

public function registered(Request $request, $user) 
{
    $user->userSetting()->create([
        'user_name' => 'u'.$user->id,
        'profile_name' => $user->name,
        'user_email' => $user->email,
        'user_private account' => 0,
        'user_fans_counter' => 1,
        'new_subscriber_alert' => 1,
        'new_tip_alert' => 1,
        'new_private_message_alert' => 1,
        'new_referral_alert' => 1,
    ]);
}

这样user_id应该通过关系自动填充。