Product model code:
public function categories()
{
return $this->belongsToMany(Category::class);
}
Category model code:
public function products()
{
return $this->belongsToMany(Product::class);
}
Product controller code:
$products = Product::with('categories')->get();
index.blade.php code:
@foreach ($products as $product)
<li>Product Name: {{$product->name}}</li>
<li>Category: {{ $product->categories->name }}</li>
@endforeach
When I use the above index.blade.php code the following error shows:
Trying to get property 'name' of non-object.
Then I tried amending the index.blade.php code into the following:
<li>Category: {{ $product->categories }}</li>
And then I got the following as the output in my index.blade.php :
[{"id":1,"name":"Cameras"}]
May I know how I can show the name of the category related to specific product?
belongsToMany
or hasMany
means this have many related models. laravel returns a collection instead of an object for these relationships. so you can't get a property directly like $product->categories->name
, as categories is a collection here. you have to loop through the collection like
@foreach ($product->categories as $category)
{{ $category->name }}
@endforeach
now you can access all the related categories to that product and get their properties.