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...
To use laravel function updateOrCreate you need auto increment id in your table.
what they are doing is
select id from your_table where your_attributes
after that get auto increment id
then
update your_table set your_values where field_id
As per the Definition of the Eloquent Model Method "updateOrCreate()"
it takes two argument ...
I am answering to this question cause I can't find any answer related to ON DUPLICATE KEY UPDATE, although I am using Laravel 5.4. If you look at the updateOrCreate method in the Laravel's core code, you will see after all Laravel is using 2 different queries: one for update and another one for create. Because of this, sometimes you can get duplicated data in the DB. So in some cases it can be useful to write this kind of raw query:
Hope it can be useful for someone.
I created a package to work with MySQL insert on duplicate key.
It may be useful for others:
https://packagist.org/packages/yadakhov/insert-on-duplicate-key
Example:
Add the follow method insertUpdate to your Model
You can use:
The next query it will be executed:
The method automatically add/remove the Eloquent timestamps if you have enabled or disabled.
In my case this was caused by a simple mismatch on the auto incrementing key in my model table.
Getting the current max id:
Then setting the sequence value one higher:
eliminated the error.