Laravel 按类别展示产品

时间:2021-06-30 16:45:29

标签: php laravel

网络路由

Route::get('/categories/{id}', [ProductController::class, 'categories'])->name('categories');

产品控制器

public function categories($id)
    {
        $categories = Category::with('product')->find($id);

        return view('products.categories')->with('products', $categories);
    }

返回 $categories 时,它会显示所选产品的类别(游戏椅:游侠游戏椅)

{"id":4,"category":"Gaming Chair","created_at":"2021-06-27T16:04:27.000000Z","updated_at":"2021-06-27T16:04:27.000000Z","product":[{"id":2,"category_id":4,"product_name":"Ranger Gaming Chair","description":"Lorem Ipsum","product_picture":"1624846316.png","price":4325.23,"created_at":"2021-06-28T02:11:56.000000Z","updated_at":"2021-06-28T02:11:56.000000Z"}]}

但每次我返回 view('products.categories') 并执行 foreach 循环

@foreach($categories as $item)
  <h5>{{ $item->category }}</h5>
  <h5>{{ $item->product_name }}</h5>
@endforeach

它显示整个类别,而不是 "Gaming Chair" :/

请帮我展示一下。

1 个答案:

答案 0 :(得分:0)

试试这个方法

在您的控制器中

    public function categories($id)
        {
           //make this variable singular not plural..its easier to read/understand
            $category = Category::with('product')->find($id); 
    
            return view('products.categories')->with('products', $categories);
        }

在你的刀片中

@foreach($category->products as $item)
  <h5>{{ $item->category_id }}</h5>
  <h5>{{ $item->product_name }}</h5>
@endforeach