0

I want to get some view data using laravel. here is my code:

public function brandsview($cate_url, $brand_url)
{        
    $brands = Brands::where('url',$brand_url)->first();
    $brand_id = $brands->id;
    $products = Products::where('brand_id',$brand_id)
        ->where('status','!=','Hide')
        ->where('status','Show')
        ->get();
   
    return view('lokalproductspage.brands')
        ->with('brands', $brands)
        ->with('products', $products);
}

I get the error trying to get property 'id' of non-object. Please help me.

rustyhu
  • 1,912
  • 19
  • 28
  • I'm guessing it didn't find a matching brand, so `$brands` is null instead of an object. – aynber Sep 16 '21 at 15:19
  • any suggestions to fix it? im just really new to this – Lauren James Borja Sep 16 '21 at 15:47
  • You can use `firstOrFail` instead of `first`, which will throw an error if the brand isn't found. If you think it should exist, try `Log::info($brand_url);` and look in your logs to make sure that it contains what you think it does. – aynber Sep 16 '21 at 15:59
  • 1
    Does this answer your question? [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – ManojKiran A Sep 16 '21 at 16:07
  • 1
    try putting return $brands instead of return view and see if that returns anything. – Exploit Sep 16 '21 at 16:16
  • please use dd($brands->id) before accessing it and check if is not null. I'm sure this is null and also check $brand_url if it has spaces before or after or is it ok? – Noman Shaikh Sep 18 '21 at 11:32
  • i follow your instruction sir nomah but it is still the same error. it is not null i also check if there spaces but still error :(( – Lauren James Borja Sep 18 '21 at 13:18

2 Answers2

0

Looks like $brands return nothing, are you checked it? If return of $brands is not stable may be u should add some checks before use attributes like 'id'

0

Change first() to firstOrFail(), which will let you know if you actually found a record. Normally your error suggests there was no record found. It is a nice way to show a 404 if the user put a bad url in.

$brands = Brands::where('url',$brand_url)->firstOrFail();
Barry Deen
  • 13
  • 2