ItSolutionStuff.com

Laravel Eloquent firstOrNew Example

By Hardik Savani • April 16, 2024
Laravel

Hi,

This tutorial is focused on laravel eloquent firstOrNew. I’m going to show you about laravel model firstornew. This post will give you simple example of laravel firstornew example. i explained simply step by step firstornew laravel example.

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

Laravel eloquent added amazing method call firstOrNew(). firstOrNew method help you to find record in database table and returns, if there is no records in database table then it will create new object instance and using save() you can store in database and return.

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

Without using firstOrNew()

<?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 firstOrNew()

<?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::firstOrNew(

[ 'name' => 'Platinum' ],

[ 'slug' => 'platinum', '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

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 inRandomOrder() Method Example

Read Now →
ā˜…

Laravel Eloquent whereNotNull() Query Example

Read Now →
ā˜…

Laravel Eloquent whereNotBetween() Query Example

Read Now →
ā˜…

Laravel Eloquent Order By Query Example

Read Now →
ā˜…

Laravel Eloquent exists() and doesntExist() Example

Read Now →
ā˜…

How to Group By with Order By Desc in Laravel?

Read Now →
ā˜…

Laravel Order By Relationship Sum Column Example

Read Now →
ā˜…

Laravel One to Many Eloquent Relationship Tutorial

Read Now →
ā˜…

Laravel Group By with Month and Year Example

Read Now →