Laravel多创建用户

时间:2016-07-24 17:32:49

标签: mysql laravel authentication

我需要在同一时间创建两个用户。这是我在AuthController中的代码:

protected function create(array $data) {

    $profile = New \App\ClientDetail();
    $profile->s_firstname = $data['s_firstname'];
    $profile->s_surname = $data['s_surname'];
    $profile->p_firstname = $data['p_firstname'];
    $profile->p_surname = $data['p_surname'];
    $profile->s_mobile_number = $data['s_mob_number'];
    $profile->s_home_number = $data['s_home_number'];
    $profile->p_mobile_number = $data['p_mob_number'];
    $profile->p_home_number = $data['p_home_number'];
    [...all the form information fields]
    $profile->save();
   /*FIRST USER TO CREATE*/ 
    if($data['s_email']) {
        $user = User::create([
            'detail_id' => $profile->id,
            'email' => $data['s_email'],
            'password' => bcrypt('secret'),
        ]);
        $user->attachRole($student);
    }
   /*SECOND USER TO CREATE*/
    if($data['p_email']) {
        $user = User::create([
            'detail_id' => $profile->id,
            'email' => $data['p_email'],
            'password' => bcrypt('secret'),
        ]);
        $user->attachRole($parent);
    }

    return $user;
}

问题是令牌仅存储于最后创建的用户。在mysql数据库中,对于第一个用户,列remember_tokennull

如何创建两个不同的令牌? 如果您有同时创建两个用户的其他最佳想法,请告诉我。

由于

1 个答案:

答案 0 :(得分:0)

尝试像这样保存用户:

$user = new User($data);
$user->save();

您必须在用户模型中声明$ fillable属性:

protected $fillable = ['email','password', 'detail_id'];

您也可以使用:

$user->profile()->associate($profile->id);

在用户模型中:

public function profile()
{
    return $this->belongsTo('App\Profile');
}

或者你可以这样做:

$profile->users()->createMany($usersData);