Is there a way to mass upsert (Insert or Update if exists) records in Laravel (MySQL database) ?
Say I have a table with:
[id:1 value:4]
[id:2 value:5]
I want to perform:
Model::massupsert([
[id:1 value:100],
[id:3 value:20]
]);
And the table afterwards to be:
[id:1 value:100]
[id:2 value:5]
[id:3 value:20]
The upsert method. Laravel 8. x's query builder comes packed with a method called upsert that will let you insert (multiple) rows that do not exist and update the rows that already exist with the new values. So, for instance, let's say, you have a table called books and it contains the following records right now.
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
A model is used as a way for questioning data to and from the table within the database. Laravel gives a basic way to do that using Eloquent ORM where each table incorporates a Model to interact with it.
Now (Oct 6, 2020), Laravel(v8.10.0) has native upsert
support. https://github.com/laravel/framework/pull/34698
Model::upsert([
['id' => 1, 'value' => 100],
['id' => 3, 'value' => 20],
], 'id');
Laravel has no native UPSERT support.
I've created a package for this: https://github.com/staudenmeir/laravel-upsert
Model::upsert([
['id' => 1, 'value' => 100],
['id' => 3, 'value' => 20],
], 'id', ['value']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With