在我的网站上我有Products
和ProductCategories
他们belongsToMany
的关系,
控制器:
$products = Products::paginate(10);
查看:
@foreach($products as $product)
{{$product->productCategories}}
@endforeach
我有这个结果:
[{"id":6,"category_name":"\u062f\u0645 \u0646\u0648\u0634 \u0647\u0627","lang":"fa",
"images":{"images":{"original":"\/uploads\/post_images\/2017\/1513065012.jpeg"},
"created_at":"2017-12-12 07:50:12",
"updated_at":"2017-12-12 07:50:12","pivot":{"products_id":44,"product_categories_id":6}}]
现在我如何在此结果中访问category_name
?
此代码对我不起作用,我收到错误:
{{$product->productCategories->category_name}}
错误:
Property [category_name] does not exist on this collection instance.
或
{{$product->productCategories['category_name']}}
错误:
Undefined index: category_name
答案 0 :(得分:1)
你需要迭代收集:
@foreach($products as $product)
@foreach($product->productCategories as $category)
{{ $category->category_name }}
@endforeach
@endforeach