Table of Contents
Description
Example
Home Backend Development PHP Tutorial Using database transactions in Laravel and catching exceptions after transaction failure

Using database transactions in Laravel and catching exceptions after transaction failure

Feb 09, 2017 am 09:23 AM
laravel php

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();
});
Copy after login
Copy after login

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();
Copy after login
Copy after login

You can also use the rollBack method to restore the transaction:

DB::rollBack();
Copy after login
Copy after login

Finally, you can submit the transaction through the commit method :

DB::commit();
Copy after login
Copy after login

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
---------------------------------------
Copy after login
Copy after login

Test point table tag:

-------------------
id       name
-------------------
Copy after login
Copy after login

Test point knowledge point association table wiki_tag_rel

----------------------------------
id          tag_id        wiki_id
----------------------------------
Copy after login
Copy after login

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(&#39;,&#39;, $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']);
     }

}
Copy after login
Copy after login

                                                                  

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();
});
Copy after login
Copy after login

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();
Copy after login
Copy after login

You can also use the rollBack method to restore the transaction:

DB::rollBack();
Copy after login
Copy after login

Finally, you can submit the transaction through the commit method :

DB::commit();
Copy after login
Copy after login

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
---------------------------------------
Copy after login
Copy after login

Test point table tag:

-------------------
id       name
-------------------
Copy after login
Copy after login

Test point knowledge point association table wiki_tag_rel

----------------------------------
id          tag_id        wiki_id
----------------------------------
Copy after login
Copy after login

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(&#39;,&#39;, $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']);
     }

}
Copy after login
Copy after login

For more articles related to using database transactions in Laravel and capturing exceptions after transaction failures, please pay attention to the PHP Chinese website!              

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

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

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

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

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

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

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

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.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

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

See all articles