DEV Community

Morcos Gad
Morcos Gad

Posted on

Database Transactions - Automatically Rollback - Laravel

Imagine with me about entering data into the database. More than one entry process will take place in a single function, and an error occurred in one of these operations. This will result in a bigger mistake at one stage of the function than not executing the entire function. Here comes the role of transactions https://laravel.com/docs/8.x/database#database-transactions
Found this source and want to share it with you because of its importance https://www.youtube.com/watch?v=u-lHNsHbZ9Q
here automatically rollback if something goes wrong

use Illuminate\Support\Facades\DB;

DB::transaction(function () {
    DB::update('update users set votes = 1'); // First operation

    DB::delete('delete from posts'); // second operation
});
Enter fullscreen mode Exit fullscreen mode

Take a look at Manually Using Transactions, you will have more fun https://laravel.com/docs/8.x/database#manually-using-transactions and afterCommit() https://laravel.com/docs/8.x/mail#queued-mailables-and-database-transactions
I hope you have fun.

Top comments (0)