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();
if(is_null($category)){
$category = Category::where("name", "apple")->first();
}
*/
//use this
$category = Category::where("name", "apple")->firstOr(fn () => abort(403));
dd($category);
}
}
Hope it can help you.
#laravel #laravel-8x #eloquent-tips