DEV Community

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

Posted on

9 2

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 :)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more