Laravel Create Record if Not Exists Example

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

use IlluminateHttpRequest;

use AppModelsProduct;

class ProductController extends Controller

{

/**

* Display a listing of the resource.

*

* @return IlluminateHttpResponse

*/

public function index()

{

$product = Product::firstOrCreate(

[ 'name' => 'Platinum' ],

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

);

dd($product);

}

}

2) Manually Check and Create

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsProduct;

class ProductController extends Controller

{

/**

* Display a listing of the resource.

*

* @return IlluminateHttpResponse

*/

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

}

}

.medrectangle-4-multi-155{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:0!important;margin-right:0!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

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

I hope it can help you…

1 thought on “Laravel Create Record if Not Exists Example”

Leave a Comment