Laravel Eloquent firstOrNew Example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

Hello Brother,

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

you can easily use eloquent firstOrNew lesson in laravel 6, laravel 7 and laravel 8 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 lessons, without firstOrNew() and with firstOrNew() lesson 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.

Recent Posts

Related Posts