php - Can firstOrCreate be treated atomically in Laravel? -
i have api application hooks upload user data. each peice of data belongs user , user's email address included in each api request. if email doesn't exist in users table new user created, otherwise new data added under existing user.
i need if firstorcreate
guaranteed return user
object if 2 api request made back. in current code, querying database , if user doesn't exist create one. having issue if 2 api calls made back, 2 inserts database (two users same email). have since added unique constraint on email column want sure if use firstorcreate
able proceed after knowing either have existing user or have created on.
laravel firstorcreate
not have atomic guards. but, since have unique
constraint on column, database enforce atomicity you. thus:
$params = [ 'email' => 'foo@example.com', /* ... */ ]; try { $user = user::firstorcreate($params); } catch (\illuminate\database\queryexception $ex) { $user = user::firstorcreate($params); }
if fails first time, you've got contention. retries attempt. presumably, second attempt return first record matching. however, warned illuminate\database\queryexception
may occur multitude of reasons, unique key violations being 1 of them. second attempt may made still not return user.
Comments
Post a Comment