Laravel: Is it good practice to put all my code inside a database transaction? Event no database query codes?

I create a subscription and collaboration! 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 the queries to be executed in the database transaction. can i put all the above code in closing a Laravel transaction?

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

I mean, I have so many php code and no request logic, like sending email ... Is this a good practice? If this is not so, what should I do?

+5
source share
1 answer

According to Laravel docs:

You can use the transaction method in the database phase to start a set of operations in a database transaction. If an exception is thrown in a Closure transaction, the transaction will be automatically discarded. If Closure is successful, the transaction will be automatically completed.

You use transactions when the set of operations you perform with a database must be atomic.

That is, they all must succeed or fail. Nothing in between.

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

Bad practice to create a transaction always?

It depends on the context in which you are talking here. If this is an update, I highly recommend using transactions explicitly. If it is SELECT, then NO (explicitly).

+3
source

Source: https://habr.com/ru/post/1274894/


All Articles