No, Laravel is not handling race conditions.
You can validate that the user does not exist, but before you create the user, another thread might create a user with the same name.
How are you serving these tests (what web server?)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Race conditions in laravel and simple php
Today I wrote 2 of the same codes in laravel and simple PHP without a framework to check race conditions. In simple PHP code, race condition happens when I send requests concurrently by the Jmeter tool but in the same scenario, laravel has no race condition problem.
I want to ensure that. Is laravel handling race conditions on its own?
this is simple PHP:
<?php
if(empty($_GET['name'])){
exit('name is required');
}
try {
$conn = new PDO("mysql:host=localhost;dbname=databasename", 'user', 'pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (?,?,?)");
$numRowsStmt = $conn->prepare("Select * from users where name = ?");
$numRowsStmt->execute([$_GET['name']]);
$numRows = $numRowsStmt->rowCount();
if($numRows <= 0){
$name = $_GET['name'];
$email = rand(100,50000) . '@gmail.com';
$pass = 'password';
$stmt->execute([$name,$email,$pass]);
exit('user created');
}
exit('user exists');
} catch(PDOException $e) {
echo $e->getMessage();
}
this is laravel:
Route::get('/100/{name}', function (Request $request, $name) {
$r = Validator::make(compact('name'), ['name' => 'unique:users,name']);
if ($r->fails()) {
exit('its exist');
};
User::create(['name' => $request->name, 'email' => rand(100, 80000) . '[email protected]', 'password' => \Illuminate\Support\Facades\Hash::make(rand(100,50000)),]);
});
I know these codes are not clean I use this only to test what I want the other things are unnecessary. thanks.
@Shayanys obviously the Laravel code is going to be 100 x slower than a single php file (possibly 1000s x slower) so the possibility of a clash are many times reduced with the framework. It does not mean its impossible though.
You need to find a scenario that causes an issue (maybe running the test 1000's of times) so that you can then validate a solution.
Yes, locking the table is probably the only solution although a cache lock is a simpler solution if you have a fast cache.
A solution too specific to this example would be a unique index on the name column.
Please or to participate in this conversation.