Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 Create or Update on Duplicate

In Laravel 5.1, for MySQL insert, I want to see if the record already exists and update on duplicate or create new if none exists.

I have already searched SO where the answers were for old laravel versions. In one of the old topics it said that a new updateOrCreate() method was added in core last year. But when I try that, I am getting the error:

Integrity constraint violation: 1062 Duplicate entry '1' for key 'app_id'  

This is the query I use:

AppInfo::updateOrCreate(array(     'app_id' => $postData['appId'],     'contact_email' => $postData['contactEmail'] )); 

Where app_id is the unique foreign key in that table and I want to update the record if exists or create a new one. I have tried searching the 5.1 docs and couldn't find the info I need. Can someone guide me here please...

like image 233
Neel Avatar asked Jul 25 '15 08:07

Neel


1 Answers

As per the Definition of the Eloquent Model Method "updateOrCreate()"

function updateOrCreate(array $attributes, array $values = []){}

it takes two argument ...

  1. one is the attributes using which you want to check in database if the record is present
  2. second is the new attribute values that you want to create or update

AppInfo::updateOrCreate(['app_id' => $postData['appId']],                         ['contact_email' => $postData['contactEmail']]); 
like image 155
MrPandav Avatar answered Sep 30 '22 06:09

MrPandav