Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Is this a good practice to put all my code inside DB transaction? Event none DB query codes?

I am creating a subscribing and teaming! system.

Here is the pseudo code:

    $sub = Sub::create($sub_data);

    if(request for new team){
       $team = Team:create($team_data)
       Mail::queue....// sending email and notif
       // some php code here
    }
    elseif(request to join a team) 
    {
       $team = Team:find($team_data)
       $team->subscriber()->create($team_data) // a team has many subscribers
       Mail::queue....// sending email and notif
       // some php code here
    }
     // Here some extra queries... 

Now I want all queries to be executed in a DB transaction. can I put all the above code in Laravel Transaction closure?

DB::transaction(function()
{
 // all the above code here 
});

I mean having so many php code and none Query logic, like sending Email... Is this a good practice? If it isn't, what should I do?

like image 413
Ahmad Mobaraki Avatar asked Oct 16 '22 23:10

Ahmad Mobaraki


1 Answers

Acording to Laravel docs:

You may use the transaction method on the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction Closure, the transaction will automatically be rolled back. If the Closure executes successfully, the transaction will automatically be committed.

You use transactions when the set of database operations you are making needs to be atomic.

That is - they all need to succeed or fail. Nothing in between.

Transactions are to be used to ensure that the database is always in a consistent state.

Is a bad practice to create a transaction always?

It depends on what context you are talking here. If it is an update, then I would highly recommend using TRANSACTIONS explicitly. If it is a SELECT then NO (explicitly).

like image 78
Luis felipe De jesus Munoz Avatar answered Nov 02 '22 08:11

Luis felipe De jesus Munoz