Search code examples
laravel-5on-duplicate-key

on duplicate key update in laravel 5.0 eloquent


I have a table "app_sessions" in my database with two unique keys - device_id and device_token. I want to insert a new session in this table only if the record with device_id or device_token doesn't exist, otherwise just update the session for this record.

We can do this with a "insert .... on duplicate key update ....." query. But how can we achieve this using laravel 5.0 eloquent.

Note: We all know the other ways to do it, like fetching the record first and then inserting or updating depending on the results.


Solution

  • https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_updateOrCreate

    User::updateOrCreate(['email'=>'[email protected]'],['name'=>'foobar']);
    

    This will check for a user matching the first array, and then either update that with the second array or create a new user with that name and email.