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

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 updateOrInsert() 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

				
					DB::table('tableName')->updateOrInsert([Conditions],[fields with value]);
				
			

How to use it

				
					// Using the DB Method
DB::table('post')->updateOrInsert(
    ['id' => '10001'],
    ['name' => 'How to make it', 'created_at' => now()]
);
				
			
				
					// Using the model
Posts::updateOrInsert(
        ['id' => '10001'],
        ['name' => 'How to make it', 'created_at' => now()]]
);
				
			

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

If the id already exists in the posts table, the values of name and created_at 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 updateOrInsert() method determines whether a record exists in the database. In the above example, the id 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.

This page may contain affiliate links, which help support our project. Read our affiliate disclosure.