Home / Snippets / How to Update or Create Model in Laravel
How to Update or Create Model in Laravel cover

How to Update or Create Model in Laravel


2 years ago


Sometimes you might come across the need to update a model if it does already exist and if it doesn't then create it scenario in Laravel and that's totally possible.

Laravel updateOrCreate Model

The code that you need is "updateOrCreate()" method and this code will first try to update the model if it does already exist and otherwise it will create a new modal.

use App\Models\Post;

    ['slug' => 'hello'],
    ['title' => 'Hello World', 'slug' => 'hello', 'created_at' => now()]
The method accepts 2 parameters and the 1st one will be the "where" condition to find the existing record and the 2nd one will be the value to be updated or created. This method is very powerful and handy at the same time allowing your code to perform updating or creating logic in a single line of code.

Laravel udpateOrInsert using Fluent (DB Facade)

You can also make use of the "updateOrInsert()" method and this is available for the DB facade. This method works exactly the same as "updateOrCreate" and you can refer the code below for the full implementation.

use Illuminate\Support\Facades\DB;

    ['slug' => 'hello'],
    ['title' => 'Hello World', 'slug' => 'hello', 'created_at' => now()]

Other Reads

notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.






Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this