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, 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get Last 10 Records in Laravel?
- How to Check Database Connection in Laravel?
- How to Write Text on Existing PDF File in Laravel?
- How to Convert JSON to Array in Laravel?
- Laravel Cashier Stripe Subscription Example Tutorial
- How to Get Columns Names from Model in Laravel?
- Laravel Contact Form Send Email Tutorial
- How to Send Email to Multiple Users in Laravel?
- How to use Google Recaptcha V3 in Laravel App?
- Laravel Send SMS to Mobile with Nexmo Example
- How to Send SMS using Twilio in Laravel?
- Laravel Chartjs Chart Example Tutorial