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

406

2 years ago

0 comments

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.
<?php

use App\Models\Post;

Post::updateOrCreate(
    ['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.
<?php

use Illuminate\Support\Facades\DB;

DB::table('posts')->updateOrCreate(
    ['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.

Topics:

Frontend

Resource

Average

Average

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