ItSolutionStuff.com

Laravel Create Record if Not Exists Example

By Hardik Savani • April 16, 2024
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, laravel 9, laravel 10 and laravel 11 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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Get Last 10 Records in Laravel?

Read Now →

How to Check Database Connection in Laravel?

Read Now →

How to Write Text on Existing PDF File in Laravel?

Read Now →

How to Convert JSON to Array in Laravel?

Read Now →

Laravel Cashier Stripe Subscription Example Tutorial

Read Now →

How to Get Columns Names from Model in Laravel?

Read Now →

Laravel Contact Form Send Email Tutorial

Read Now →

How to Send Email to Multiple Users in Laravel?

Read Now →

How to use Google Recaptcha V3 in Laravel App?

Read Now →

Laravel Send SMS to Mobile with Nexmo Example

Read Now →

How to Send SMS using Twilio in Laravel?

Read Now →

Laravel Chartjs Chart Example Tutorial

Read Now →