In this blog, We will be going to learn about firstOr 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 firstOr method with examples.
The firstOr method retrieves the first Model from a query, or if no matching Model is found, it will call a callback passed.
Let's get started,
<?php
namespace App\Http\Controllers;
use App\Models\Category;
class CategoryController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
/*
We can ignore to write this query.
$category = Category::where("name", "Mobile")->first();
if(is_null($category)){
$category = Category::where("name", "Laptop")->first();
}
*/
$category = Category::where("name", "Mobile")->firstOr(function () {
return Category::where("name", "Laptop")->first();
});
dd($category);
}
}
I hope you understood the use of firstOr method. If you have any doubt let me know in comments.
0 Comments