Call to undefined method Illuminate\Database\Query\Builder::firstOrFail()

2.9k Views Asked by At

I tried to follow but still got the error

Call to undefined method Illuminate \ Database \ Query \ Builder :: firstOrFail()

enter image description here

enter image description here

2

There are 2 best solutions below

0
Nathan On

Query Builder does not have the firstOrFail(); method, it's only available to Eloquent models, for example if tbl_product was a Product model then it would be:

  $product_info = Product::where('product_id', $productId)->firstOrFail();

If you want to use Query Builder, then you could do the following:

 $product_info = DB::table('tbl_product')->where('product_id', $productId)->first();

    if ($product_info === null)
        throw \Exception('Product not found');
0
A.A Noman On

In Eloquent model you have to use firstOrFail method

$product_info = Product::where('product_id'=>$productId)->firstOrFail();

Or you have to use

$product_info = Product::where('product_id'=>$productId)->first();