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

450

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

Alaz

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 ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this