Laravel Eloquent firstOr() Example
This tutorial will provide example of laravel firstOr. i would like to show you laravel eloquent firstor example. if you want to see example of laravel firstor example then you are a right place. we will help you to give example of firstor in laravel.
Here i will give you very simple example of how to use firstOr() with laravel eloquent. you can easily use firstOr() with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.
Sometime, you need to write logic for default value. when you find some product from database and it's not match any record then you can return default product. so you have to write long logic behind this but laravel eloquent provide firstOr() where you can easily return default object.
Let's see example:
firstOr() Example:
<?php
namespace App\Http\Controllers;
use App\Models\Category;
class SignaturePadController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
/*
We can ignore to write this query.
$category = Category::where("name", "Mobile2")->first();
if(is_null($category)){
$category = Category::where("name", "Laptop")->first();
}
*/
$category = Category::where("name", "Mobile2")->firstOr(function () {
return Category::where("name", "Laptop")->first();
});
dd($category);
}
}
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent withMin(), withMax() and withAvg() Example
- Laravel Eloquent withSum() and withCount() Example
- Laravel Eloquent updateOrCreate Example
- Laravel Eloquent firstOrNew Example
- Laravel Eloquent firstOrCreate Example
- Laravel Eloquent Group By Example
- Laravel Eloquent exists() and doesntExist() Example
- Laravel Eloquent Where Query Examples
- Laravel One to One Eloquent Relationship Tutorial
- Laravel Many to Many Eloquent Relationship Tutorial