


Using database transactions in Laravel and catching exceptions after transaction failure
Description
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.
Example
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']); } }
Description
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.
Example
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Validator can be created by adding the following two lines in the controller.

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide
