错误-试图获取非对象的属性-在Laravel中

时间:2019-07-01 20:32:43

标签: laravel eloquent laravel-5.7

当我从categorey表中获取categorey名称时,出现了问题。 此处的代码..

谢谢。

 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) 试图获取非对象enter image description here的属性

1 个答案:

答案 0 :(得分:0)

错误很直接。您还没有获得$ category_name变量的任何对象,并且试图访问name属性的值。因为没有对象,所以未定义。

添加一个简单的条件即可解决此问题

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'));
}

要将数据发送到刀片服务器:

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

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