类别名称未显示在产品索引中

category name is not showing at products index

您好,我在产品索引页面获取产品,我想显示产品所属类别的名称,因此仅显示类别 ID,但未显示类别名称

blade 文件:

@foreach($products as $product)
<tr>
    <td>
        <a href="{{ route('admin.product.show', $product->id) }}" style="color: #37333d;">
            {{ ucwords($product->product_name) }}
        </a>
    </td>
    <td>{{ $product->product_slug }}</td>
    <td>{{ $product->category_id }}{{ $product->category_name }}</td>
</tr>
@endforeach

产品控制器:

public function index()
{
    $products = Product::all();
    return view('admin.product.index', compact('products'));
}


product.php

      class Product extends Model
      {
      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');
        }
      }```

category model:

       class Category extends Model
       {
          protected $fillable = [
         'category_name', 'category_description', 'category_slug', 'category_image'
       ];

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

1. check your Product.php is their category_name exit or not

2.  where are from category name which model product or category.
  if in category you should get relationship between category and product 


if category name from category model
your code is

public function index()
{
    $products = Product::with('category')->get();
    return view('admin.product.index', compact('products'));
}

make relationship one to one between product & category

1- 在您的产品模型中创建关系

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

2- 在您的 Blade 文件中调用此关系以获得类别的名称:

<td>{{ $product->category_id }}{{ $product->category->name }}</td>

首先在您的控制器更改中:

public function index()
{
    $products = Product::with('category')->get();
    return view('admin.product.index', compact('products'));
}

那么在你看来你可以做到:

<td>{{ $product->category_id }}{{ $product->category->category_name }}</td>

如果您对此解决方案有任何错误,请在此处提供。

祝你好运!