DEV Community

Cover image for Laravel 9 Update an Existing Model
Code And Deploy
Code And Deploy

Posted on

Laravel 9 Update an Existing Model

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/laravel-9-update-an-existing-model

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();
Enter fullscreen mode Exit fullscreen mode

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']);
Enter fullscreen mode Exit fullscreen mode

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'
    ]);
Enter fullscreen mode Exit fullscreen mode

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]);
Enter fullscreen mode Exit fullscreen mode

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-9-update-an-existing-model if you want to download this code.

Happy coding :)

Top comments (0)