Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joeljerushan's avatar

Returning Data when no Results

Hi Fist of all Im Completely New to Laravel i have a function in my Controller like this

    public function getSinglePurchase($id){
            return DB::table('purchasespayment')
                    ->where("fk_purchases","=",$id)
                    ->orderBy('date', 'desc')->first();
     }
     public function show($id){
        $purchase_info = $this->getSinglePurchase($id);
        return view('purchase.view',compact('purchase_info');
    }

and when i return this data to view if there is data on return my view is working fine. and when there is no data for example my view file looks like this

{{ purchase_info.amount }}

whenever my controller returns nothing to view i get following error "Trying to get property 'amount ' of non-object"

I Managed to Fixe that error like following

@if (!empty($purchase_info)) 
    {{ $purchase_info->amount}}
  @endif 

this method working fine but i have almost 10 to 15 items to get like this do i need to check !empty method everytime or is there any easy way to get or check empty values via Controller. Please Advice

0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67

Use firstOrFail() instead of first(). If you use route-model-binding, it does that automatically. It will just produce a 404 error, which makes sense if the thing you're requesting doesn't exist.

I'm not entirely positive whether that exists using the query builder like you are, but it works if you're using Eloquent Models (which are better anyway).

https://laravel.com/docs/5.6/eloquent#retrieving-single-models

1 like
joeljerushan's avatar

Thank You Read everything for almost 8 hours and found how it's Works <3 #laravel

Please or to participate in this conversation.