0

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.

janardhan
  • 3
  • 3

1 Answers1

0

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

User::updateOrCreate(['email'=>'foo@bar.com'],['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.

Jeff
  • 24,623
  • 4
  • 69
  • 78
  • I got this error: MassAssignmentException in Model.php line 452: device_token. When I used this function, I kept the device_id same but different device_token. But the updateOrCreate function checks for both the columns (device_id and device_token) with and condition. Jeff, are you getting my question? – janardhan Jun 24 '16 at 15:32
  • You need to have `device_token` in the `$fillable` array on the model if you want to be able to update it with an array. The first array should be the conditions you want to check if it already exists, and the second array is the ones you want to update. – Jeff Jun 24 '16 at 18:50
  • but this is not working if we have two conditions. Here, we need to check if `device_id` exists **OR** `device_token` exists. But, `updateOrCreate` function only accepts `and condition`. – janardhan Jun 25 '16 at 11:35
  • Ah I understand. You might need to do two separate queries. Sorry for the confusion! – Jeff Jun 25 '16 at 21:12