I am relatively new to Laravel and I want to know more about the behavior of the following code inside an API controller method (i.e. defined in routes/api.php).
DB::connection($dbName)->beginTransaction();
Assuming two people simultaneously access to the server and two controller instances are created. Now both instances calls DB::connection($dbName)->beginTransaction();)
and executes some code before commiting.
To describe the situation more clearly, two people A and B both access to the same Laravel server, with two instances of the same controller class. The two controller instances both access to the same DB from the same IP address and executes the same code segment which involves the beginTransaction
.
As of my current information there are two possible things happening:
(1) They are treated as two different transactions and things such as lastInsertId are maintained separately. This is the desired behavior but I have trouble understanding how the two different instances of the controller are identified internally. Based on a rough look at Laravel source code it seems only read the config file for the specific DB connection, which is identical for both instances of the controller.
(2) They are treated as the same transaction, which is not the desired behavior. I will have to think of a way to make it work like described in (1)
Currently I don't have sufficient environment for accurately testing behavior of simultaneous controller instances so I have to ask the question here.
I have read https://laravel.com/docs/8.x/database#database-transactions but it does not tell us which of (1) or (2) it is.
It's 1st case
Transactions aren't even part of Laravel - they are part of SQL. Laravel only calls SQL.
Also in PHP each request is handles separately by spawning a new instance of script. Therefore there is no variable sharing between two requests.