laravel firstorcreate

Posted by w3diy - 6 months ago

Laravel Eloquent firstOrCreate Example

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 = 'Mobile';
        $product = Product::where('name', $name)->first();


        if (is_null($product)) {

            $product = new Product(['name' => $name]);

        }

        $product->slug = 'mobile';
        $product->detail = 'test mobile';
        $product->save();
        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::firstOrCreate(
            [ 'name' => 'Mobile' ],
            [ 'slug' => 'mobile', 'detail' => 'test mobile' ]
        );
        dd($product);

    }

}