laravel-5 - 做一个返回多个创建函数 Laravel
问题描述
刚做完一个php artisan make:auth
,app\Http\Controllers\Auth\RegisterController
就在默认的create函数里:
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
语句,以及如何从 the 中获取新创建id
的User
并将其传递给user_id
of 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"];
解决方案
如果我没记错的话,会根据函数的结果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
没有 no的结果UserInformation
,因为整个事务在失败时回滚,并在成功时持久化到数据库中。
推荐阅读
- c# - 传递具有从所需类型派生的类型的泛型对象
- r - R 表示组是否有值
- javascript - Django 并在不同视图中向外部 API 发布请求
- python - 是否有用于处理和验证用户输入的 Python 库?
- java - 为什么 java.util.logging 没有将日志写入文件?
- c++ - 带有字符串数组的递归二进制搜索
- android - Xamarin Android 安装标志
- javascript - Fullcalendar 4,使用 eventRender 时出现错误解析 JSON 失败
- html - 在 HTML 日期输入中更改 Chrome 日历图标的颜色
- docker - 用于 grpc-web 的带有 Docker 的 Envoy 代理。在浏览器上使用 ssl 会导致 ERR_CERT_COMMON_NAME_INVALID