In this blog, We will be going to learn about firstOrNew method in Laravel Eloquent.
You know that Laravel already has some standard methods like create(), update(), make(), and save().
But Laravel includes some other methods also which are also useful for creating and updating that I have been using in many projects.
We will understand firstOrNew method with examples.
The firstOrNew method is really useful for finding the first Model that matches some constraints or making a new one if there isn’t one that matches those constraints.
Let's get started,
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();
}
$product->name=$name;
$product->slug = 'platinum';
$product->detail = 'test platinum';
$product->save();
dd($product);
}
}
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 understood the use of firstOrNew. If you have any doubt let me know in comments.
0 Comments