In this tutorial, we will learn about how database records update in Laravel. Update record is one of the CRUD (Create, Read, Update, Delete) operation in Laravel. Updating records is common feature in most of the CMS, Admin Panels, CRM, etc. So let’s just jump into it and learn the database records update in Laravel step by step with various techniques.
Table of Contents |
1. Using save() Method |
2. Using update() Method |
3. Using updateOrCreate() Method |
4. Update Multiple Records Using upsert() In Laravel |
5. Using updateOrInsert() Method |
Update In Laravel
In this tutorial, we will take a simple example of blog post. So we need Post
model. You can easily create model by running the following command.
php artisan make:model Post -m
After running the above command a new model file created in app/Models
directory. If you are using an older version than Laravel 8 then it will be created in app/
directory.
The -m
flag on the above command denotes that create migration file along with model creation. So you can find new migration files in database/migrations
folder.
Now, let’s open newly created migration files and update the up()
method as below:
Post Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
* One to many relationship tutorial
* scratchcode.io
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
* One to many relationship tutorial
* scratchcode.io
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Now run the below command to create posts
table in your database:
php artisan migrate
Now, let’s update the records in Laravel by following various methods.
01 Using save() Method
As the name suggest, the save() method is used to save the records. In this method, first we need to find the record and then we can add additional data into it and then we save the records. Thus, it will update the records in database.
$post = Post::find(1);
$post->title = "Updated title";
$post->description = "Updated description";
$post->save();
02 Using update() Method
The update() method is used to update the records as the name suggest. We can use it with where condition as below:
$affectedRecords = Post::where("id", 3)->update(["title" => "Updated title"]);
03 Using updateOrCreate() Method
The updateOrCreate() method will update the record if found else it will create a new one. Define what you want to update in the first argument. The second argument of this function is unique which behave like a where condition.
$post = Post::updateOrCreate(
['title' => 'New or update title', 'description' => 'this is description'],
['id' => 1] // Like where condition
);
04 Update Multiple Records Using upsert() In Laravel
The upsert() is very interesting function in Laravel. This function is used to update the multiple records in Laravel.
You just need to define what you want to update in first argument but with some unique fields, and in second argument define the which fields are unique for update and in third argument list out the fields which will actually be updated in the database.
We tried to create following example for better understanding.
Model::upsert([
[ 'field1' => 'value', 'field2' => 'value', 'field3' => 'value', ........ ],
[ 'field1' => 'value', 'field2' => 'value', 'field3' => 'value', ........ ],
[ 'field1' => 'value', 'field2' => 'value', 'field3' => 'value', ........ ],
],
[ 'field1', 'field2' ], // Unique field like where condition
[ 'field3' ], // These fields will be updated in db
)
Let’s now fit our Post example into it. So we have id
, title
and description
fields in posts
table.
In that id
is unique field for us while two other can be updatable. Let’ update the records of ids 11, 7 & 9 using upsert().
Post::upsert([
[ 'id' => 11, 'title' => 'update or create 11', 'description' => 'test 11' ],
[ 'id' => 7, 'title' => 'update or create 7', 'description' => 'test 7' ],
[ 'id' => 9, 'title' => 'update or create 9', 'description' => 'test 9' ],
],
[ 'id' ], // Unique field like where condition
[ 'title', 'description' ], // These fields will be updated in db
)
In this back process, upsert() behave like a loop update. So all the 3 above records will be in loop and title
and description
column updated with where id
condition. So simple right?
05 Using updateOrInsert() Method
The updateOrInsert method is similar like a updateOrCreate() Sometimes you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used.
The differences are:
- The
updateOrCreate
method returns model, whereasupdateOrInsert
returns boolean value. updateOrCreate
is method of Eloquent Builder andupdateOrInsert
is method of Query Builder.
DB::table('posts')
->updateOrInsert(
['title' => 'updated title', 'description' => 'updated description'],
['id' => '7']
);
Additionally, read our guide:
- Laravel One To One Relationship Tutorial
- Best Way to Remove Public from URL in Laravel
- How To Print Or Debug Query In Laravel
- Specified Key Was Too Long Error In Laravel
- AJAX PHP Post Request With Example
- How To Use The Laravel Soft Delete
- How To Add Laravel Next Prev Pagination
- Laravel Remove Package With Example (Correct Way)
- Difference Between Factory And Seeders In Laravel
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Calculate Age From Birthdate
- How to Convert Base64 to Image in PHP
- Check If A String Contains A Specific Word In PHP
- How To Find Duplicate Records in Database
- How To Convert Word To PDF In Laravel
- Laravel Multiple Where Conditions With Example
That’s it for now. We hope this article helped you to learn Database Records Update In Laravel.
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance. 🙂 Keep Smiling! Happy Coding!