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:
- If a record already exists in a database table, it updates that record.
- 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
1 |
DB::table('tableName')->updateOrInsert([Conditions],[fields with value]); |
How to use it
1 2 3 4 5 |
// Using the DB Method DB::table('post')->updateOrInsert( ['id' => '10001'], ['name' => 'How to make it', 'created_at' => now()] ); |
1 2 3 4 5 |
// 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 <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.