How to update a record in the database using Eloquent in Laravel?

To update a record in the database using Eloquent in Laravel, you can follow these steps:

  1. First, retrieve the record you want to update using the find or findOrFail method. For example, to update a user record with id equal to 1:
$user = User::find(1);

or

$user = User::findOrFail(1); // throws an exception if the record doesn't exist
  1. Once you have the record, you can update its attributes using the dot notation or the fill method. The dot notation directly assigns values to the attributes:
$user->name = "John Doe"; $user->email = "[email protected]"; $user->save();

or you can use the fill method to assign multiple attributes at once:

$user->fill([ 'name' => 'John Doe', 'email' => '[email protected]' ]); $user->save();
  1. Alternatively, you can use the update method to update the record in a single step. The update method accepts an array of attributes to update:
$user->update([ 'name' => 'John Doe', 'email' => '[email protected]' ]);

Note that the update method will automatically persist the changes to the database.

That's it! You have successfully updated a record in the database using Eloquent in Laravel.