We currently have an interesting problem on a system with higher access rates: We are providing an Api Call, which outputs information with appropriate parameters. At the beginning we have a call in the corresponding controller
$user = \App\Models\User::firstOrCreate([ 'email' => auth()->user()->email ]);
Now we have already had some situations where we found in the logfile the message that the email address could not be added because it already exists (email field is set to unique). In all situations the identical api call is sent three times in a row and then the error occurs. I am convinced that in a fraction of a second the situation occurs that the data set e.g. from the first call has not yet been written, the second call does not find it and tries to create it. In the meantime, the database transaction for creating the record has been executed.
My idea now would be to no longer use firstOrCreate but to execute a search (first) first. If the result is empty, I would create the data set with a Create and if necessary I would generate a short artificial pause with a sleep in the situation to be sure that the data was written. Is that so practical? The alternative would be to create the data sets in advance, but actually I wanted to create the Just in Time to reduce the amount of data to the necessary amount.
What is a good way to proceed here?