首页 > 其他分享 >How to use try-catch with DB::transaction in Laravel

How to use try-catch with DB::transaction in Laravel

时间:2024-03-08 20:22:34浏览次数:28  
标签:Laravel use transaction DB try queries catch

How to use try-catch with DB::transaction in Laravel. When adding numerous queries, DB::transaction() is used to check whether each query was properly run before rolling back. Therefore, can we use a try-catch block with db::transaction as well? Using a try-catch block will enable you to identify the error that caused the query to fail.

Table of Contents

DB::transaction() is used for inserting multiple queries to make sure every query is executed successfully or not, if not then rollback. So, can we also use a try-catch block with db::transaction and try-catch will help you to catch the error of why the query failed.

Use try-catch with DB::transaction while handling multiple queries. Use try-catch to grab errors if the db transaction fails in Laravel complete guide.

Laravel DB Transaction with Try Catch

WELL! Suppose you wrote a block of code that code will multiple times run and insert records in the database.

In detail, I have two database tables: the first, Users, and the second, GalleryOwner. If the user record is successfully inserted, then I need to run the second query in the same code block, where I need to first get the last inserted user_id and then add another record to the second table, GalleryOwner.
So, I have two insert queries that will run one after the other, and there is a possibility that the second query would fail, but how can I identify the issue and throw an Exception? We must try here…We will use a catch block in our code, as well as DB::transaction, because if any of the queries fails, the rollback is called auto. More amazing Laravel content can be found here.

Our Transactional Toolset

Database transactions consist of three possible “tools”:

  • Creating a transaction – Letting the database know that the next queries on a connection should be considered part of a transaction.
  • Rolling back a transaction – Cancelling all queries within the transaction, ending the transactional state.
  • Committing a transaction – Committing all queries within the transaction, ending the transactional state. No data is affected until the transaction is committed.

Try Catch Block with DB::transaction in Laravel

try {
    DB::beginTransaction();

    DB::insert(...);
    DB::insert(...);

    DB::delete('DELETE FROM posts WHERE status = ?');
    User::find(1)->delete();

    // all good
    DB::commit();

    // after commit you can safely trigger events or notifications or log.
    $user->notify(new OffersNotification($payloadData));

} catch (\Exception $e) {
    // something went wrong
    DB::rollback();
    
    throw new Exception($e);
}

You can send notifications after DB::commit(); But always remember don’t trigger any email notification event before commit.

Moved the beginTransaction() method call inside the try block for better exception handling.

Please note that this code assumes you are using Laravel and have the appropriate database transactions set up (beginTransaction(), commit(), and rollBack()).

Example 01 – Try Catch with DB::transaction using the above Example

<?php

// User.php
// GalleryOwner.php

public
function store(Request $request): \Illuminate\Http\RedirectResponse
{
    $res = [];

    try {
        \DB::beginTransaction();

        $user = new User;
        $user->username = $request::input('username');
        $user->email = $request::input('email');
        $user->save();

        // add last inserted user_id in GalleryOwner table.
        $gOwner = new GalleryOwner;
        $gOwner->user_id = $user->id; // last inserted id
        $gOwner->title = $request::input('title');
        $gOwner->description = $request::input('description');
        $gOwner->save();

        // also can perform delete or update quries here

        \DB::commit();

        $user->notify(new OffersNotification($payloadData));

        $res = ['success' => 'Data inserted!'];

    } catch (\Exception $e) {
        \DB::rollback();
        $res = ['error' => $e->getMessage()];
    }


    return redirect()->route('route-name')->with($res);
}

Example 02 – Laravel Database Transactions

<?php

try {
    DB::transaction(function () use ($profile) {
        $profile->avatar->forceDelete();

        DirectMessage::whereFromId($profile->id)->delete();
        StatusHashtag::whereProfileId($profile->id)->delete();
        FollowRequest::whereFollowingId($profile->id)
            ->orWhere('follower_id', $profile->id)
            ->forceDelete();
        Follower::whereProfileId($profile->id)
            ->orWhere('following_id', $profile->id)
            ->forceDelete();
        Like::whereProfileId($profile->id)->forceDelete();

        Log::success("User profile deleted with all data!");

        $profile->delete();
    });
} catch (Exception $e) {
    throw new Exception($e->getMessage());
}

$user = User::query()->where('email', '[email protected]')->firstOrFail();
$user->notify(new ProfileDeletedNotification($payloadData));

Note about DB::transaction Laravel try-catch

if the code would execute and if the query somehow failed then catch{} block execute and data rollbacked and in that case else{} block run and return an Exception. You can also throw a custom Exception in the catch block. I’ll try to make an article on this soon. If have you any questions related to this post then comment below.

Database: Getting Started – Laravel, you may already know what a transaction is. However, let’s review! A transaction gives you the ability to safely perform a set of data-modifying SQL queries (such a transaction gives you the ability to safely perform a set of data-modifying SQL queries (such as insertions, deletions, or updates). This is made safe because you can choose to rollback all queries made within the transaction at any time. For example, let’s pretend we have an application that allows the creation of accounts.

Database Transactions in Laravel, In the case you need to manually ‘exit’ a transaction through code (be it through an exception or simply checking an error state), shouldn’t Laravel provide strong support for transactions? It is a very big task for any developer to develop any complex, large application and hold data consistently. The transaction is strictly followed by the ACID property of the database. Simply help to make data consistent in every state.

Laravel: Using try-catch with DB::transaction(), Sometimes you need to do a series of SQL queries, and every one of these is so tied together that, if one fails for whatever reason, then you call rollback all queries. and try-catch block helps you to catch the error of why the query failed. A transaction starts with the first executable SQL statement and ends when it is committed or rolled back. Query inside transactions is completely safe because you can choose to rollback all queries made within the transaction at any time.

Laravel try-catch

In this tutorial, you will learn about Laravel try-catch. If you are working with the Laravel framework, you may face many errors while working. To handle these errors, you can use try…catch statements. Let’s assume that you are building a commerce web application in Laravel.

Featured Article. Some Laravel Best Practices Every Developer Should Know Real-Time Broadcasting with Laravel 7.x Vuejs and Pusher Laravel 8.x API Permissions Using Passport Scope Laravel and N + 1 Problem | How To Fix N + 1 Problem Laravel 8.x Queues Example with Redis and Horizon How to Use Circuit Breaker Design Pattern in Laravel Avoid Pivot Table and Use Json Column in Laravel

Hi Guys, In this example, I will learn you how to use try-catch in Laravel. you can easily and simply use try-catch in Laravel. you often see default Laravel texts like “Whoops, something went wrong” or, even worse, the exception code, which is not helpful at all to the visitor.

Laravel nested transactions

Transaction Inside Transaction (nested transactions), I’m using Laravel 8 & MySQL (InnoDB). Will nested transactions work? For example, DB::transaction(function () { // Some code Saw an issue on laravel/framework about nested transactions and was wondering. What are some use-cases for this? And if a transaction is nested inside another one, but the rollback/commit only happens for the ‘outer’ transaction, what’s the benefit of the nested transaction? Please sign in or create an account to participate in this conversation.

How do Nested Transactions work in Laravel?, In Laravel 6 you can use: DB::connection(DB::getDefaultConnection())->​transactionLevel(). to get the current active transaction number. I’m using Laravel 5.2 and wants to implement nested transaction. [Middleware]- applied for all logics, commits on normal end and rollbacks when exception caused. public function handle($request, Closure $next){ \DB::beginTransaction(); try { $response = $next($request); } catch (\Exception $e) { \DB::rollBack(); throw $e; } if ($response instanceof Response && $response->getStatusCode() > 399) { \DB::rollBack(); } else {

[Proposal] Nested transactions · Issue #1823 · laravel/framework, Since no one is interested in discussing this in the forums (http://forums.laravel.io/​viewtopic.php?id=9610) I’ll post it here. Would it be possible For those who arrived here like me, to search about Laravel’s nested DB transaction support: the issue mentioned above is #1795, which is a duplicate of #1686, and the important thing to know is that yes, it supports nested transactions – it has been implemented.

Laravel transaction rollback

Creating a transaction – Letting the database know that the next queries on a connection should be considered part of a transaction; Rolling back a transaction – Cancelling all queries within the transaction, ending the transactional state; Committing a transaction – Committing all queries within the transaction, ending the transactional state. No data is affected until the transaction is committed.

Manually Using Transactions. If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the beginTransaction method on the DB facade: DB::beginTransaction(); You can rollback the transaction via the rollBack method: DB::rollBack(); Lastly, you can commit a transaction via the commit method:

How to avoid “email taken” if something goes wrong after registration? One way is to use DB Transactions and Rollback full operation, here’s how.

Db::begintransaction();

What is the difference between DB::beginTransaction() and DB , DB::beginTransaction() will only begin a transaction, while for DB::transaction() you must pass a Closure function that will be executed inside a transaction. The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.

Database Transactions in Laravel, Start transaction beginTransaction(); // Run Queries $acct = createAccount(); $​user DB::beginTransaction(); try { // Validate, then create if valid $newAcct Examples. The following example creates an OleDbConnection and an OleDbTransaction.It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods.. public void ExecuteTransaction(string connectionString) { using (OleDbConnection connection = new OleDbConnection(connectionString)) { OleDbCommand command = new OleDbCommand(); OleDbTransaction transaction = null; // Set the

PDO::beginTransaction – Manual, PDO::beginTransaction — Initiates a transaction $this->hasActiveTransaction = parent::beginTransaction (); whatever db actions you have and then: DB::beginTransaction() will only begin a transaction, while for DB::transaction() you must pass a Closure function that will be executed inside a transaction. So this: DB::transaction(function() { // Do something and save to the db }); is the same as this.

 

FAQ’s

Why we need Laravel try-catch with DB::transaction()

Sometimes you need to do a series of SQL queries, and every one of these is so tied together that, if one fails for whatever reason, then you call rollback all queries. and try-catch block helps you to catch the error of why the query failed.

Example try-catch with DB::transaction in LaravelDB::beginTransaction();
try {
DB::insert(…);
DB::insert(…);
DB::delete(…);
DB::commit(); // all good
} catch (\Exception $e) {
DB::rollback(); // something went wrong
}

标签:Laravel,use,transaction,DB,try,queries,catch
From: https://www.cnblogs.com/mouseleo/p/18061784

相关文章

  • 利用.user.ini文件隐藏后门
    0x00前言在PHP中有个很有趣的东西叫.user.ini,有点类似.htaccess文件,PHP会在每个目录下扫描INI文件,我们可以通过.user.ini文件来实现隐藏后门的效果官方手册地址:传送门通过阅读手册,我们知道在.user.ini中可以识别PHP_INI_PERDIR和PHP_INI_USER模式的INI设置关于PHP_INI_*一......
  • User Agent 数据解释说明
    Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/114.0.0.0Safari/537.36UA字符串各部分的含义如下:Mozilla/5.0:表示当前浏览器所使用的用户代理标识符的版本号。它几乎是一个固定的写法。(WindowsNT10.0;Win64;x64):表示......
  • 解决 Android studio Connect to 127.0.0.1:[/127.0.0.1] failed: Connection refused
    前言由于代理变更,androidstudio会有一系列报错,其中一个是Connectto127.0.0.1:xxxxxx[/127.0.0.1]failed:Connectionrefused网上答案大都太片面了,无法完全解决问题,这里列举出四个可能的原因,希望对大家有用问题如下建议一下四种方案都尝试下,我相信总有一种能......
  • docker-compose部署单机clickhouse
    【转载:https://www.cnblogs.com/crow1840/p/17506884.html】1、创建clickhouse目录[root@localhostdocker]#lsgitlab_dockerjenkins_dockermysql_docker[root@localhostdocker]#mkdirclickhouse/conf-p2.创建docker-compose.yml[root@localhostclickhouse]#cat......
  • 运行时遇到Oracle错误1017 invalid username/password;login denied
    参考链接:https://answer.baidu.com/answer/land?params=7elCyy2%2BVQFLNLJM1h81dr5QZQQgc1gH3Jx0mKtGyC9iN883lLAjVKkqqFwgT9IkwDSCCV6LpBhAaZmXkqXteDsXxjanzrzpWVxBkZhfR3Unz5gw02%2BImYJ2Z%2Bvnm92UuArsoipr6J4Lg4wWW8llDohcXIR6bJhJl2%2Fy598QiTvvwPJAYShha1DQ3DoUCfGRi%2BD......
  • Django Custom Authentication | Registration, Login, Logout, ResetPassword, UserP
    Startaprojectdjango-adminstartprojectregistrationFormProjectdirectoryregistration/settings.py#ApplicationdefinitionINSTALLED_APPS=['django.contrib.admin',#Usedforauthentication'django.contrib.auth',......
  • vscode 的sync的问题RequestFailed (UserDataSyncError) syncResource:unknown operat
    024-03-0708:58:24.361[error]RequestFailed(UserDataSyncError)syncResource:unknownoperationId:unknown:Connectionrefusedfortherequest'https://vscode-sync.trafficmanager.net/v1/manifest'.atu.D(c:\Debug\VSCode\resources\app\ou......
  • Laravel 中 faker 的方法总结
    Laravel中faker的方法总结428513 liuguowei163的个人博客 /  1878 /  13 / 创建于 4年前 / 更新于4年前 安装composerrequirefzaninotto/faker可通过在 config/app.php 增加如下配置使其支持中文:'faker_locale'=>'zh_CN',基本用法Fake......
  • MAC OS :ERROR: Failed to open file '\Users\futantan\Downloads\atguigudb.sql'
    在操作source\Users\futantan\Downloads\atguigudb.sql的时候出现ERROR: Failedtoopenfile'\Users\futantan\Downloads\atguigudb.sql',error:2 解决方案,在对应的路径下开启mysql udandandeMacBook-Pro:mysqlfutantan$mysql-uroot-pEnterpassword:Welcom......
  • Caused by: org.apache.ibatis.reflection.ReflectionException: Error parsing prope
    问题描述1、编译过程是不会被发现的;2、运行时报错:Causedby:org.apache.ibatis.reflection.ReflectionException:Errorparsingpropertyname'lambda$pages$4d14352e$1'.Didn'tstartwith'is','get'or'set'。问题分析MyBatis-Plus的条件构造器常用......