我正在学习Laravel,工作于5.22。我试图将两条记录保存到两个表中,但只有在两个方面都成功的情况下才提交更改,否则我希望它失败并回滚。
我的保存控制器代码是:
public function store(Request $request)
{
$all = $request->all();
// we need to fill in who is the creator of this new user,
$all['creator_user_id'] = Auth::user()->id;
// Commit both updates or fail and rollback
DB::transaction(function ($all) {
$client = Client::create($all);
$orgClient['organisation_id'] = $client->organisation_id;
$orgClient['client_id'] = $client->client_id;
OrganisationClient::create($orgClient);
});
return redirect()
->route('client.index')
->withMessage([
'type' => 'success',
'value' => 'Client <strong>' . $all->client_name . '</strong> successfully created.']);
}
此操作失败,错误为:
Type error: Argument 1 passed to Illuminate'Database'Eloquent'Model::create() must be of the type array, object given, called in /home/vagrant/Code/simply-invoice/app/Http/Controllers/ClientController.php on line 80
我的问题似乎是将$all
传递给闭包。如果我从闭包参数中移除$all
,那么我得到undefined variable all
。我该怎么做?谢谢
您将$all
设置为回调参数,而不是use
。transaction
回调目前正在接收Illuminate'Database'Connection
的实例作为参数。
为了获得您想要的实际变量,您必须将回调更改为:
// ....
DB::transaction(function () use($all) {
// ...