Laravel Create Record if Not Exists Example

By Hardik Savani September 30, 2022 Category : Laravel

Hello Friends,

In this example, you will learn laravel create record if not exists. you will learn laravel db insert if not exists. you'll learn how to create record if not exists in laravel. you'll learn laravel insert data if not exist. follow the below step for create record if not exists in laravel.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

There are two ways to create a record if not exist in laravel. I will give you the following two examples:

1) Using firstOrCreate()

2) Manually Check and Create

So, let's see the below example code:

1) Using firstOrCreate()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Product;

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);

}

}

2) Manually Check and Create

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Product;

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(['name' => $name]);

}

$product->slug = 'platinum';

$product->detail = 'test platinum';

$product->save();

dd($product);

}

}

I hope you will understand how it works and how it helps you.

I hope it can help you...

Tags :