Need help implementing createOrFirst logic in Laravel Query Builder to prevent race conditions #55000
Unanswered
mohammadrasoulasghari
asked this question in
Q&A
Replies: 1 comment
-
Update /**
* Attempt to create the record. If a unique constraint violation occurs, attempt to find the matching record.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model|static
*/
public function createOrFirst(array $attributes = [], array $values = [])
{
try {
return $this->withSavepointIfNeeded(fn () => $this->create(array_merge($attributes, $values)));
} catch (UniqueConstraintViolationException $e) {
return $this->useWritePdo()->where($attributes)->first() ?? throw $e;
}
}
The logic is not in Eloquent or query builder but: See \Illuminate\Database\MySqlConnection::isUniqueConstraintError
and \Illuminate\Database\Connection::runQueryCallback We implemented the duplicate check like this: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I’m working on a PR that requires implementing functionality similar to Eloquent’s createOrFirst() method, but using Laravel’s Query Builder instead.
In my PR, Mr Otwell commented: “It’s a bit more atomic to follow createOrFirst logic so there isn’t a race condition.”
After investigating, I couldn’t find any built-in Query Builder method that provides the same atomic operation as Eloquent’s createOrFirst(). While Eloquent has this functionality built-in to handle unique constraints safely, I’m not sure if there’s an equivalent in Query Builder or if I need to implement this logic myself.
My question is:
Is there any built-in infrastructure in Query Builder for handling unique constraints similar to Eloquent’s createOrFirst() method? Or do I need to implement this functionality myself? If I need to implement it, what’s the best approach to ensure atomicity and prevent race conditions?
Here’s the PR I’m working on: [Link to PR
I would be grateful if anyone could guide me on how to implement it.🙏]
Beta Was this translation helpful? Give feedback.
All reactions