To update a record in the database using Eloquent in Laravel, you can follow these steps:
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
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();
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.