I want to lock a table inside a transaction. Something like this:
DB::transaction(function (){
DB::statement('LOCK TABLES important_table WRITE');
//....
});
However, the line DB::statement('LOCK TABLES important_table WRITE');
always triggers the following error:
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. (SQL: LOCK TABLES officeSeal WRITE)
How can I lock the table in Laravel?
Laravel Create Table Step 1: To create a table we need to use the create method which is available on the Schema facade. The schema has got... Step 2: The rename method can be used for the purpose of renaming the table. The drop method helps to drop a particular... Step 3: You can update your ...
. Database transactions and pessimistic locking are probably not the most used features, however, they can be extremely useful. Let’s take a brief look and then examine how Laravel’s database layer supports these features. In this post, we don’t focus on the plain SQL implementation of database transactions or locking.
However, if you insist, you could use Laravel's Pessimistic Locking. Namely, sharedLock () and lockForUpdate () methods, as mentioned in the documentation. You'd notice that the example in the documentation doesn't use Eloquent, but relies on Query Builder.
In order to show the Laravel Datatables example, we must have some data in the backend. To fill this gap, we will create some dummy data, and Faker will help us complete this task. Add the values in database/seeds/DatabaseSeeder.php. We need to create a EmployeeController and here we write the code to render records from the database.
One can lock a table in Laravel like this:
DB::raw('LOCK TABLES important_table WRITE')
;
As pointed out in the comments by other users too, I don't feel certain that a table lock is absolutely the only way out. However, if you insist, you could use Laravel's Pessimistic Locking. Namely, sharedLock()
and lockForUpdate()
methods, as mentioned in the documentation.
You'd notice that the example in the documentation doesn't use Eloquent, but relies on Query Builder. However, this Q&A seems to suggest that it can be done with Eloquent too.
It may also be worthwhile to have a read through this article which contrasts Pessimistic and Optimistic locking implementations in Laravel.
DB::unprepared('LOCK TABLES important_table WRITE'); this one worked for me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With