首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Laravel按类别显示产品

Laravel按类别显示产品
EN

Stack Overflow用户
提问于 2021-07-01 00:45:30
回答 1查看 37关注 0票数 0

Web路由

代码语言:javascript
运行
复制
Route::get('/categories/{id}', [ProductController::class, 'categories'])->name('categories');

ProductController

代码语言:javascript
运行
复制
public function categories($id)
    {
        $categories = Category::with('product')->find($id);

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

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

代码语言:javascript
运行
复制
{"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"}]}

但每次我返回视图(‘products.categories’)并执行foreach循环时

代码语言:javascript
运行
复制
@foreach($categories as $item)
  <h5>{{ $item->category }}</h5>
  <h5>{{ $item->product_name }}</h5>
@endforeach

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

请帮我展示一下。

EN

回答 1

Stack Overflow用户

发布于 2021-07-01 02:56:42

试试这条路

控制器中的

代码语言:javascript
运行
复制
    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);
        }

和刀片式服务器中的

代码语言:javascript
运行
复制
@foreach($category->products as $item)
  <h5>{{ $item->category_id }}</h5>
  <h5>{{ $item->product_name }}</h5>
@endforeach
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68198699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档