Posts Learn Components Snippets Categories Tags Tools new About
/

How to Update or Create Model in Laravel

Learn how to update or create a model automatically in Laravel. Get to know how to perform this action easily using the "updateOrCreate" method

Created on Oct 29, 2021

38 views

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

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

)