Muneeb
Muneeb

Reputation: 105

ERROR - Trying to get property of non-object - in laravel

I am getting the problem when i fetch categorey name from categorey table .. code here ..

Thanks.

 public function viewProducts(){

     $products = Product::get();
     $products = json_decode(json_encode($products));

     foreach($products as $key => $val){
        $category_name = Category::where(['id'=>$val->category_id])->first();
        $products[$key]->category_name= $category_name->name;
     }
     echo "<pre>";print_r($products);die;

     return view('admin.products.view_products')->with(compact('products'));
}

ErrorException (E_NOTICE) Trying to get property of non-objectenter image description here

Upvotes: 0

Views: 1468

Answers (1)

X 47 48 - IR
X 47 48 - IR

Reputation: 1498

The error is straight forward. You haven't gotten any objects of $category_name variable and you're trying to access to the value of the name property. Which is not defined because there's no object.

Add a simple condition to fix it like this

public function viewProducts(){
  $products = Product::get();
  $products = json_decode(json_encode($products));

  foreach($products as $key => $val){
    $category_name = Category::where(['id'=>$val->category_id])->first();
      if($category_name != null){
        $products[$key]->category_name= $category_name->name;
      }
    }
  echo "<pre>";print_r($products);die;

  return view('admin.products.view_products')->with(compact('products'));
}

To send data to your blade:

# Controller:
$data['category_name'] = $category_name;
$data['products'] = $products;
->withKeyName($data);

# Blade:
{{ $KeyName['category_name'] }}
{{ $KeyName['products'] }}

Upvotes: 1

Related Questions