2016-04-12 123 views
0

我正在學習Laravel,工作於5.22。我試圖將兩條記錄保存到兩個表中,但只有在兩條路都成功時才提交更改,否則我希望它失敗並回滾。Laravel 5.2執行多個數據庫事務,然後提交或回滾失敗

爲救我的控制器代碼:

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。我該怎麼做呢?謝謝!

回答

2

您正在將$all設置爲回調參數而不是usetransaction回調正在接收Illuminate\Database\Connection的實例作爲參數。

爲了得到你想要的,你有你的回調改變這一實際變量:

// .... 
DB::transaction(function() use($all) { 
// ... 
+0

感謝@Roj Vroemen,相互學習的今天! – TheRealPapa