Avoid duplicate entry constraint violation with Laravel
<p>I have a mySQL table for user devices with a column <code>device_id</code>, which has a <code>UNIQUE</code> constraint assigned to.</p>

<p>In my Laravel application, my <code>APIController</code> class provides an API to add new devices to the table. The method looks like this:</p>

<pre><code>public function postDevice(Request $request)
{
    $user = Auth::user();

    if(!$request-&gt;has('device_id'))
        return response()-&gt;json(['error' =&gt; 'You need to provide a unique device identifier "device_id".'], 460);

    $device_id = $request-&gt;input('device_id');

    $device = UserDevice::where('device_id', $device_id)-&gt;first();

    if($device) {
        // update device properties with transmitted data
        $device-&gt;fill($request-&gt;all());

        // make sure this device belongs to our user
        $device-&gt;user()-&gt;associate($user);

        $device-&gt;save();
    } else {
        // create new device for our user
        $user-&gt;devices()-&gt;create($request-&gt;all());
    }

    return response()-&gt;json(['status'=&gt;'success']);
}
</code></pre>

<p>I thought that my condition would make sure that the uniqueness constraint cannot be violated through this API. But somehow I regularly get errors like this:</p>

<pre><code>Integrity constraint violation: 1062 Duplicate entry 'C02P69YWG3QC' for key 'user_devices_device_id_unique' (SQL: insert into 'user_devices' ('device_id', 'mac_model', 'mail_version', 'mailbutler_version', 'osx_version', 'user_id', 'updated_at', 'created_at') values (C02P69YWG3QC, MacBook Pro (Retina, 15-inch, Late 2013), 10.0 (3225), 6439, 10.12.0, 13400, 2016-09-13 12:17:56, 2016-09-13 12:17:56))
</code></pre>

<p>Do you have any idea how the constraint can be violated with the code shown above?
Is there a better coding paradigm to avoid such errors?</p>

<p>BTW: I am running this application with potentially multiple instances working on the same DB. Could there be a race condition involved?</p>