How to Update a Record Using Laravel Eloquent?

When it comes to updating records we need to first find the record. Then after that whole process is quite similar to Insertion or Creation actually. Let’s code this.

$contact = Contact::findOrFail( 67 );

$contact->name = "Jon Archer Jr.";
$contact->save();

Here in the first line we just use findOrFail() and then we just need to set the value of that column as property which we want to update. Then we called save() method. We can also do this in one line.

$contact->update( [ "name" => "Jon Archer Jr." ] );

We can update more than one record as well. For that we need to call update() method with array of column names as key. Confusing? Let’s code that to clear the confusion.

Contact::whereDate( 'created_at', '<', '2021-03-28' )
->update( [ 'vip' => false ] );

Here we are selecting all records which were created before 28th of March 2021 and then we are setting vip status to false. We can pass more than one elements in array if we want to update multiple columns.

Contact::whereDate( 'created_at', '<', '2021-03-28' )
->update( [ 'vip' => false, 'votes' => '0' ] );

I hope now updating records using Laravel eloquent won’t be a problem for you. If you have any question please write a comment. We really appreciate that.