Laravel Eloquent firstOrCreate Method With Example

 

In this blog, We will be going to learn about firstOrCreate 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 firstOrCreate method with examples.


The firstOrCreate method is very similar to the firstOrNew method. It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new Model after applying any attributes passed in the second parameter.


Let's start with examples,


Without 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()

    {

        $name = 'Platinum';

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

  

        if (is_null($product)) {

            $product = new Product();

        }

  

        $product->name = $name;

        $product->slug = 'platinum';

        $product->detail = 'test platinum';

  

        $product->save();

  

        dd($product);

    }

}


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::firstOrCreate(

            [ 'name' => 'Platinum' ],

            [ 'slug' => 'platinum', 'detail' => 'test platinum' ]

        );

  

        dd($product);

    }

}


I hope you understand how to use firstOrCreate method. If you have any doubts let me know in comments.