Table of contents
In this post, I will show you an example of how to implement using Laravel 9 on Update an Existing Model. Laravel model update is one of the most functionality we should learn when creating an application using Laravel. In this post, we have different methods and examples of how to do it. Just pick one that is suitable for your needs.
Â
Example #1:
Â
$employee = Employee::find(1);
$employee->name = "Juan Dela Cruz";
$employee->save();
Â
Example #2:
We can also update the model using an array with multiple values which don't need to use the save()
method.
Â
$employee = Employee::find(1);
$employee->update(['name' => 'Juan Dela Cruz', 'address' => 'My address']);
Â
Example #3:
We can also update records with a conditional method using where
function directly.
Â
Employee::where('salary', '>', '10000')
->update([
'address' => 'Juan Dela Cruz',
'address' => 'My address'
]);
Â
Example #4:
If you don't need to change the updated_at
column when updating the record you may use the touch
option as false
so that the model will exclude it.
Â
$employee = Employee::find(1);
$employee->update([
'name' => 'Juan Dela Cruz',
'address' => 'My address'
], ['touch' => false]);
Read next