AmoyCreative

Read Time: 2 minutes |

How to use the updateOrInsert() method in Laravel Query?

Learning Laravel can be daunting, and following the documentation can be confusing. In this document, I will discuss and outline how to use the updateOrInsert() method in a Laravel query builder.

Background

The  <a href="https://laravel.com/docs/9.x/queries#update-or-insert" rel="noreferrer noopener" target="_blank"><strong>updateOrInsert()</strong></a> method in Laravel’s query builder does two things:

  1. If a record already exists in a database table, it updates that record.
  2. If the record doesn’t exist, it inserts a new one.

This method is helpful when you want to make sure that a record is in the database and up-to-date, without having to manually check if it’s already there before updating or inserting it.

Its return type is Boolean.

Syntax

How to use it

In this example, we’re updating or inserting a record in the  <strong>posts</strong> table with a new value for the  <strong>name</strong> and  <strong>created_at</strong> fields, and specifies the id  <strong>10001</strong>.

If the id already exists in the  <strong>posts</strong> table, the values of  <strong>name</strong> and  <strong>created_at</strong> fields will be replaced with the new values. If the id doesn’t exist, a new record will be added with the specified values.

The second argument in  <strong>updateOrInsert()</strong> method determines whether a record exists in the database. In the above example, the  <strong>id</strong> field is used to identify whether a record exists. You can use any field or combination of fields that uniquely identifies a record in the table.