未定义变量:行(视图:resources\views\admin\category\show.blade.php)

Undefined variable: row (View: resources\views\admin\category\show.blade.php)

嗨,我想展示与其相关的类别中的产品,但它说:

Undefined variable: row (View:\resources\views\admin\category\show.blade.php)

blade 文件:

@foreach($row->products as $pro_data)
      {{ $pro_data->product_name }}
@endforeach

我把上面的代码写成了show.blade.php

类别模型:

  protected $fillable = [
 'category_name', 'category_description', 'category_slug', 'category_image'
];

public function product()
{
    return $this->hasMany('App\Product');
}

产品型号:

  protected $fillable = [
 'product_name', 'product_description', 'product_image', 'category_id', 'product_code', 'product_price', 'product_status', 'product_slug'
];

public function category()
{
    return $this->belongsTo('App\Category');
}

类别控制器:

  public function show(Category $category)
  {
    return view('admin.category.show', compact('category'));
  }
  1. 变量名不同

如您所见,您已经在 Controller 中压缩了变量名称类别。

您正在 blade 文件中使用 $row

将 .blade.php 文件中的 $row 替换为 $category

@foreach($category->products as $pro_data)
      {{ $pro_data->product_name }}
@endforeach
  1. 关系名称不同

将 $row 更改为 $category 后,将 Product 模型中的关系名称从 product 更改为 products。

类别模型:

...

public function products()
{
    return $this->hasMany('App\Product');
}

...
//Category controller  
public function show(Category $category){
    $category = $category->with('product')->get();
    return view('admin.category.show', compact('category'));
  }

// blade
@foreach($category->product as $pro_data)
      {{ $pro_data->product_name }}
@endforeach