Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mass upsert in Laravel (Eloquent)

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]
like image 994
Yaron Avatar asked Apr 07 '19 11:04

Yaron


People also ask

How does Upsert work in laravel?

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.

What is eloquent ORM in laravel?

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.

What is model in laravel?

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.


2 Answers

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');
like image 130
baijunyao Avatar answered Sep 28 '22 07:09

baijunyao


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']);
like image 21
Jonas Staudenmeir Avatar answered Sep 28 '22 06:09

Jonas Staudenmeir