This post demonstrates how to use database transactions both for Eloquent ORM and Laravel’s Query Builder.
The DB Facade
Generally, we use the following construct (there is another similar construct too!).
1 2 3 4 5 | DB::transaction(function() { // Codes using Eloquent models and // Query Builder }); |
For example,
1 2 3 4 5 6 7 8 9 | DB::transaction(function() { $product = new Product(); $product->name = 'Product A'; $product->price = 100; $product->save(); DB::table('products')->where('is_deleted', '=', 1)->delete(); }); |
For more information, please visit https://laravel.com/docs/5.7/database
Return Value from Transaction
We can return value from DB::transaction function. For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | ... public function store(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'description' => 'required', 'price' => 'required|integer|max:999999|min:0' ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $fn_create = function() use ($request) { $input = $request->all(); try { $product = new Product(); $product->name = $input['name']; $product->description = $input['description']; $product->price = $input['price']; $vendor = Auth::user()->vendor()->get(); $product->vendor()->associate($vendor[0]); $product->save(); return response()->json(['success'=>json_decode ("{}")], $this->successStatus); } catch(Exception $e) { return response()->json(['error'=>'Unable to create'], 400); } }; $return = DB::transaction($fn_create); return $return; } ... |