只需完成php artisan make:auth
,app\Http\Controllers\Auth\RegisterController
中便包含默认的创建函数:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
我在此默认视图(/register
)的同一页面的视图中添加了另一个模型的生日。如何在相同的默认创建函数中插入新的创建函数?
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"];
答案 0 :(得分:0)
如果我没记错的话,根据return Model::create(...);
函数的结果,true
会简单地返回false
或create()
(或因错误而死亡),因此我们可以调整代码以处理此问题。请尝试以下操作:
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}},因为整个事务都会在失败时回滚,并成功保存到数据库。