返回多个创建函数Laravel

时间:2019-01-22 15:27:56

标签: laravel-5

只需完成php artisan make:authapp\Http\Controllers\Auth\RegisterController中便包含默认的创建函数:

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

我在此默认视图(/register)的同一页面的视图中添加了另一个模型的生日。如何在相同的默认创建函数中插入新的创建函数?

enter image description here

UserInformation::create([
    'user_id' => ???
    'birth_date' => $data['birth_dae']
]);

如何将其连接到上面的return语句,以及如何从id获取新创建的User并将其传递给以下对象的user_id UserInformation

到目前为止我的想法:

protected function create(array $data)
{
    return [
        User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        ]),
        UserInformation::create([
        'user_id' => ??? // should be the same as the id of the created user
        'birth_date' => $data['birth_date'],
        'color' => "blue"
        ])
    ];
}

试图做这样的事情:

protected function create(array $data)
{
    $user = new User;
    $user->name = $data['name'];
    $user->email = $data['email'];
    $user->password = Hash::make($data['password']);
    $user->save();

    $user_id = $user->id;

    $user_info = new UserInformation;
    $user_info->user_id = $user_id;
    $user_info->birth_date = $data['birth_date'];
    $user_info->color = "blue";
    $user_info->save();

    return view('home');
}

但仍然返回此错误:

  

传递给Illuminate \ Auth \ SessionGuard :: login()的参数1必须   实施Illuminate \ Contracts \ Auth \ Authenticatable接口,   Illuminate \ View \ View给定的实例

编辑:

我的一个好朋友推荐了这个

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'pasword' => Hash::make($data["password"])
    ]);

    UserInformation::create([
        'user_id' => $user->id,
        'birth_date' => $data['birth_date'],
        'color' => 'blue'
    ]);

    return $user;
}

在我的UserInformation模型中:

protected $fillable = ["user_id", "birth_date", "color"];

1 个答案:

答案 0 :(得分:0)

如果我没记错的话,根据return Model::create(...);函数的结果,true会简单地返回falsecreate()(或因错误而死亡),因此我们可以调整代码以处理此问题。请尝试以下操作:

protected function create(array $data){
  \DB::beginTransaction();

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

    $userInformation = UserInformation::create([
      "user_id" => $user->id,
      "birth_date" => $data["birth_date"],
      "color" => "blue"
    ]);
  } catch(\Exception $ex){
    \DB::rollBack();
    \Log::error("Error creating User and UserInformation: ".$ex->getMessage());

    return false;
  }

  \DB::commit();

  return true;
}

通过将$user设置为User::create()的结果,可以在后续的$user->id中使用UserInformation::create()。另外,我建议在保存相关记录时使用事务。如果User::create()成功,而UserInformation::create()失败,那么您将不会得到没有User的{​​{1}},因为整个事务都会在失败时回滚,并成功保存到数据库。