Reputation: 17360
in my web site i have Products
and ProductCategories
which they are belongsToMany
relationship, with
Controller:
$products = Products::paginate(10);
View:
@foreach($products as $product)
{{$product->productCategories}}
@endforeach
i have this result:
[{"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}}]
now how can i access to category_name
in this result?
this code don't work for me and i get error:
{{$product->productCategories->category_name}}
error:
Property [category_name] does not exist on this collection instance.
or
{{$product->productCategories['category_name']}}
error:
Undefined index: category_name
Upvotes: 1
Views: 157
Reputation: 163968
You need to iterate over collection:
@foreach($products as $product)
@foreach($product->productCategories as $category)
{{ $category->category_name }}
@endforeach
@endforeach
Upvotes: 1