Home > Article > Backend Development > Using database transactions in Laravel and catching exceptions after transaction failure
In Laravel, if you want to run a set of operations in a database transaction, you can use the transaction method in the DB facade. If an exception is thrown within a transaction's closure, the transaction will be automatically restored. If the closure runs successfully, the transaction will be automatically committed. You don't need to worry about manually reverting or committing the transaction when using the transaction method:
DB::transaction(function () { DB::table('users')->update(['votes' => 1]); DB::table('posts')->delete(); });
Manual operation of transactions
If you want to manually handle the transaction and have full control over the restore or commit operation , you can use the beginTransaction
method in the DB facade:
DB::beginTransaction();
You can also use the rollBack method to restore the transaction:
DB::rollBack();
Finally, you can submit the transaction through the commit method :
DB::commit();
Note: The transaction method of the DB facade can also be used to control the query statement builder and Eloquent ORM transactions.
Suppose you want to store a knowledge point in the database. This knowledge point belongs to two different test points at the same time. That is, the two data of test points and knowledge points are many-to-many. relationship, then three tables are needed to implement this data structure:
Knowledge point table wiki:
--------------------------------------- id title content ---------------------------------------
Test point table tag:
------------------- id name -------------------
Test point knowledge point association table wiki_tag_rel
---------------------------------- id tag_id wiki_id ----------------------------------
Now we need to open the transaction to add Wiki data. After the new wiki is successfully added, associate it with the specified test point
(When using the query builder or Eloquent ORM to execute query in laravel , if it fails, Illuminate\Database\QueryException will be returned)
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Database\QueryException; use App\Wiki; class TestController extends Controller { //用DB facade的事务方法控制 查询语句构建器的事务 public function storeWiki(Request $request) { DB::beginTransaction(); try { $tagIds = explode(',', $request->get('tag_id')); $wiki_id = DB::table('wiki')->insertGetId([ 'title' => $request->get('title'), 'content' => $request->get('content') ]); $relationData = []; foreach($tagIds as $tagId) { $data = ['wiki_id' => $wiki_id, 'tag_id' => $tagId]; $relationData[] = $data; } DB::table('wiki_tag_rel')->insert($relationData); DB::commit(); } catch(\Illuminate\Database\QueryException $ex) { DB::rollback(); return \Response::json(['status' => 'error', 'error_msg' => 'Failed, please contact supervisor']); } return \Response::json(['status' => 'ok']); } //用DB facade的事务方法控制 Eloquent ORM的事务 public function createWiki(array $data) { DB::beginTransaction(); try { $tagIds = explode(',', $data['tag_id']); $newWiki = Wiki::create([ 'title' => $data['title'], 'content' => $data['content'] ]); //Wiki和Tag两个Model使用了belongsToMany建立了多对多的关系 //通过attach方法来附加wiki和tag的关系(写入中间表) $newWiki->tags()->attach($tagIds); DB::commit(); } catch(QueryException $ex) { DB::rollback(); return \Response::json(['status' => 'error', 'error_msg' => 'Failed, please contact supervisor']); } return \Response::json(['status' => 'ok']); } }
In Laravel, if you want to run a set of operations in a database transaction, you can use the transaction method in the DB facade. If an exception is thrown within a transaction's closure, the transaction will be automatically restored. If the closure runs successfully, the transaction will be automatically committed. You don't need to worry about manually reverting or committing the transaction when using the transaction method:
DB::transaction(function () { DB::table('users')->update(['votes' => 1]); DB::table('posts')->delete(); });
Manual operation of transactions
If you want to manually handle the transaction and have full control over the restore or commit operation , you can use the beginTransaction
method in the DB facade:
DB::beginTransaction();
You can also use the rollBack method to restore the transaction:
DB::rollBack();
Finally, you can submit the transaction through the commit method :
DB::commit();
Note: The transaction method of the DB facade can also be used to control the query statement builder and Eloquent ORM transactions.
Suppose you want to store a knowledge point in the database. This knowledge point belongs to two different test points at the same time. That is, the two data of test points and knowledge points are many-to-many. relationship, then three tables are needed to implement this data structure:
Knowledge point table wiki:
--------------------------------------- id title content ---------------------------------------
Test point table tag:
------------------- id name -------------------
Test point knowledge point association table wiki_tag_rel
---------------------------------- id tag_id wiki_id ----------------------------------
Now we need to open the transaction to add Wiki data. After the new wiki is successfully added, associate it with the specified test point
(When using the query builder or Eloquent ORM to execute query in laravel , if it fails, Illuminate\Database\QueryException will be returned)
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Database\QueryException; use App\Wiki; class TestController extends Controller { //用DB facade的事务方法控制 查询语句构建器的事务 public function storeWiki(Request $request) { DB::beginTransaction(); try { $tagIds = explode(',', $request->get('tag_id')); $wiki_id = DB::table('wiki')->insertGetId([ 'title' => $request->get('title'), 'content' => $request->get('content') ]); $relationData = []; foreach($tagIds as $tagId) { $data = ['wiki_id' => $wiki_id, 'tag_id' => $tagId]; $relationData[] = $data; } DB::table('wiki_tag_rel')->insert($relationData); DB::commit(); } catch(\Illuminate\Database\QueryException $ex) { DB::rollback(); return \Response::json(['status' => 'error', 'error_msg' => 'Failed, please contact supervisor']); } return \Response::json(['status' => 'ok']); } //用DB facade的事务方法控制 Eloquent ORM的事务 public function createWiki(array $data) { DB::beginTransaction(); try { $tagIds = explode(',', $data['tag_id']); $newWiki = Wiki::create([ 'title' => $data['title'], 'content' => $data['content'] ]); //Wiki和Tag两个Model使用了belongsToMany建立了多对多的关系 //通过attach方法来附加wiki和tag的关系(写入中间表) $newWiki->tags()->attach($tagIds); DB::commit(); } catch(QueryException $ex) { DB::rollback(); return \Response::json(['status' => 'error', 'error_msg' => 'Failed, please contact supervisor']); } return \Response::json(['status' => 'ok']); } }
For more articles related to using database transactions in Laravel and capturing exceptions after transaction failures, please pay attention to the PHP Chinese website!