Laravel Eloquent firstOr() Query Example

Sometime, you need to write logic for default data. when you find some data from database and it's not match any record then you can return default data. In this scenario you have to write long logic behind this but laravel eloquent released firstOr() where you can easily return default object.

Here i am to give you very simple example of how to use firstOr() with laravel eloquent. you can easily use firstOr() with laravel.This tutorial will provide the query example of laravel firstOr.

Let's see the example of firstOr query:

namespace App\Http\Controllers;
use App\Models\Category;
class TestController extends Controller
     * Write code on Method
     * @return response()
    public function index()
            We can ignore to write this query.
            $category = Category::where("name", "apple")->first(); 
                $category = Category::where("name", "apple")->first();             
        //use this
        $category = Category::where("name", "apple")->firstOr(fn () => abort(403));  


Hope it can help you.


Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js