Laravel Eloquent updateOrCreate Method With Example

 

In this blog, We will be going to learn about updateOrCreate method in Laravel Eloquent.

You know that Laravel already has some standard methods like create(), update(), make(), and save().

But Laravel includes some other methods also which are also useful for creating and updating that I have been using in many projects. 

We will understand updateOrCreate method with examples.


The updateOrCreate method attempts to find a Model matching the constraints passed as the first parameter. If a matching Model is found, it will update the match with the attributes passed as the second parameter. If no matching Model is found a new Model will be created with both the constraints passed as the first parameter and the attributes passed as the second parameter.


Without using updateOrCreate()


<?php

   

namespace App\Http\Controllers;

  

use App\Models\Product;

use Illuminate\Http\Request;

  

class ProductController extends Controller

{

    /**

     * Display a listing of the resource.

     *

     * @return \Illuminate\Http\Response

     */

    public function index()

    {

        $name = 'Platinum';

        $product = Product::where('name', $name)->first();

  

        if (!is_null($product)) {

            $product->update([

                'price' => 130,

                'price_update_date' => date('Y-m-d')

            ]);

        }else{

            $product = Product::create([

                'name' => 'Platinum',

                'price' => 130,

                'price_update_date' => date('Y-m-d')

            ]);

        }

  

        dd($product);

    }

}



With using firstOrCreate()


<?php

  

namespace App\Http\Controllers;

  

use App\Models\Product;

use Illuminate\Http\Request;

  

class ProductController extends Controller

{

    /**

     * Display a listing of the resource.

     *

     * @return \Illuminate\Http\Response

     */

    public function index()

    {

        $product = Product::updateOrCreate(

            [ 'name' => 'Platinum' ],

            [ 'price' => 130, 'price_update_date' => date('Y-m-d') ]

        );

  

        dd($product);

    }

}


I hope you understood the use of updateOrCreate. If you have any doubt let me know in the comments.