o.oedits
o.oedits

Reputation: 51

View Many to Many Relationship in laravel

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?

Upvotes: 0

Views: 343

Answers (3)

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4271

As categories is a collection, you can iterate over it or benefit from laravel collection methods and pluck your desired property out of it.

By convertin the result of pluck method to array, you can implode them and show it as a string. Below code may help you:

implode(', ', $product->categories->pluck('name')->toArray())

Upvotes: 0

Donkarnash
Donkarnash

Reputation: 12835

@foreach ($products as $product)
  <li>Product Name: {{$product->name}}</li>
    <ul>
      @foreach($product->categories as $category)
        <li>Category: {{ $category->name }}</li>
      @endforeach
    </ul>
@endforeach

$product->categories is a collection of related category records for the $product object not an object - hence the error

Upvotes: 0

zahid hasan emon
zahid hasan emon

Reputation: 6233

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.

Upvotes: 1

Related Questions