Web路由
Route::get('/categories/{id}', [ProductController::class, 'categories'])->name('categories');
ProductController
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"}]}
但每次我返回视图(‘products.categories’)并执行foreach循环时
@foreach($categories as $item)
<h5>{{ $item->category }}</h5>
<h5>{{ $item->product_name }}</h5>
@endforeach
它显示整个类别,而不是"Gaming Chair" :/
请帮我展示一下。
发布于 2021-07-01 02:56:42
试试这条路
控制器中的
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
https://stackoverflow.com/questions/68198699
复制相似问题