ItSolutionStuff.com

Laravel Eloquent firstOrCreate Example

By Hardik Savani • April 16, 2024
Laravel

Hi,

I am going to explain you example of laravel eloquent firstOrCreate. this example will help you laravel model firstorcreate. it's simple example of laravel firstorcreate example. you will learn firstorcreate laravel example.

you can easily use eloquent firstorcreate example in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.

Laravel eloquent added amazing method call firstOrCreate(). firstOrCreate method help you to find record in database table and returns, if there is no records in database table then it will create new record and returns.

I will show you simple examples, without firstOrCreate() and with firstOrCreate() example so you will understand how it's helps you.

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

}

}

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' => 'Platinum' ],

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

);

dd($product);

}

}

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

i hope it can help you.

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

Delete All Records from Table in Laravel Eloquent

Read Now →

Laravel Eloquent take() and skip() Query Example

Read Now →

Laravel Eloquent whereNotNull() Query Example

Read Now →

Laravel Eloquent whereBetween() Query Example

Read Now →

Laravel Eloquent whereRaw Condition Example

Read Now →

How to Group By with Order By Desc in Laravel?

Read Now →

Laravel Order By Relation Column Example

Read Now →

Laravel Eloquent WhereNotIn Query Example

Read Now →

How to Create and Use Query Scope in Laravel Eloquent

Read Now →

How to use whereHas with orWhereHas in Laravel?

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →