Home > other >  Laravel insertion in database in same time
Laravel insertion in database in same time

Time:12-27

welcome My system opens the registration every day according to the capacity specified for each country in the table of capacities, and the registration is closed if the number of registered persons is greater than the specified capacity. I am using a condition in the laravel, if the capacity is greater, it is not saved in the database But the problem is if more than one user in the same second wanted to save, it will exceed the capacity and condition How do you solve this problem?

CodePudding user response:

This is more an SQL question than a Laravel question, what you need to do is lock your table for writing, make your queries on the other table then unlock the first one

https://www.mysqltutorial.org/mysql-table-locking/

CodePudding user response:

You have some alternatives:

Queues

Basically all the web requests are received by the broke and store them in a queue. Then the messages are consuming one by one for the listener (server side language. Php in your case). So no matter how many request at the same time are received, your backend will attend them one by one

SQL: LOCK and UNLOCK TABLES

To provide concurrency control and prevent uncontrolled data access, all the databases (oracle, sqlserver, mysql, etc) allows you to explicitly acquire a shared or exclusive table lock on the specified table. The table lock lasts until the end of the current transaction.

Here some snippet with oracle:

LOCK TABLE Maps IN EXCLUSIVE MODE;
SELECT MAX(map_id)   1 FROM Maps;
INSERT INTO Maps . . .

You just need to write the lock statement or search a framework who write it for you. There are a lot of theory and configurations that you need to read to choose the best for your requirement:

Lock at thread level

In another languages like java, there are features to ensure that some method, which executes a piece of logic marked with synchronized becomes a synchronized block, allowing only one thread to execute at any given time.

public synchronized void synchronisedInsert() {
  //logic
}

The most similar on php that I found is:

  • Related