ItSolutionStuff.com

Laravel Eloquent firstOr() Example

By Hardik Savani • April 16, 2024
Laravel

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

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

Laravel Eloquent withMin(), withMax() and withAvg() Example

Read Now →

Laravel Eloquent withSum() and withCount() Example

Read Now →

Laravel Eloquent updateOrCreate Example

Read Now →

Laravel Eloquent firstOrNew Example

Read Now →

Laravel Eloquent firstOrCreate Example

Read Now →

Laravel Eloquent Group By Example

Read Now →

Laravel Eloquent exists() and doesntExist() Example

Read Now →

Laravel Eloquent Where Query Examples

Read Now →

Laravel One to One Eloquent Relationship Tutorial

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →