Database deadlock is the situation when two or more entities are blocking some sources, and none of them is able to finish. Here is how to fix it.

 

Situation with deadlocks usually is happening on LIVE environment, when more users at the same time are trying to perform some DB actions.
But we do not want this to happen on live. How we can simulate this in dev enviroment?

 

Well, we can manually lock a table! In this example, we will lock "posts" table:

                    DB::raw('LOCK TABLES posts WRITE');
                  

 

OK, now when the table is locked we can not write into it anymore. So if we try something like this:

                    $postModel = new Post();
$postModel->save($data_array);
                  

we will get an error...

So how to fix this?

 

Actually there are two possible options:, to use queue or to try using transaction repeatedly.
In this tutorial we will show you how to use DB transactions repeatedly until they are done, or until number off attempts is exceeded.

To achieve this, we can use Laravel  transactions and define how many times we can try until it throws exception error:

                    DB::transaction(function() use($data_array) {

  return Auth::user()->post()->create($data_array);

},5);  // try 5 times
                  

 

More info about this you can find in official  documentation:

https://laravel.com/docs/8.x/database#handling-deadlocks