Trying to get property 'name' of non-object

Posted 5 months ago by incridible

When i delete the sub category(having products) of main category then it deletes but when i click on view-products then it says: Trying to get property 'name' of non-object, and showing the error line in ProductsController which is: $category_name = Category::where(['id' => $val->category_id])->first(); $products[$key]->category_name = $category_name->name; }

here is code of ProductsController:

  public function viewProducts(Request $request){
    $products = Product::get();
    foreach($products as $key => $val){
        $category_name = Category::where(['id' => $val->category_id])->first();
        $products[$key]->category_name = $category_name->name;
    $products = json_decode(json_encode($products));
    //echo "<pre>"; print_r($products); die;
    return view('admin.products.view_products')->with(compact('products'));

any solution about it,

Please sign in or create an account to participate in this conversation.