Hola
Hola

Reputation: 2233

Laravel : How to access many to many relationship data Ask

I have category and subcategory table with many to many relationship

class Category extends Model {

    protected $table='categories';
    protected $fillable=['name'];
    public function subcategories() {
        return $this->belongsToMany('App\Modules\Subcategory\Models\Subcategory', 'categories_subcategories', 'category_id', 'subcategory_id');
    }
}

Subcategory

class Subcategory extends Model {

    protected $table='subcategories';
    protected $fillable=['name'];

    public function categories()
    {
        return $this->belongsToMany('App\Modules\Category\Models\Category', 'categories_subcategories', 'subcategory_id', 'category_id');
    }

}

in controller

public function catSubList()
    {
        $subcategories = Subcategory::with('categories')->get();
        return view('Subcategory::category_subcategory',compact('subcategories'));
    }

But in view when i tried to access the data with following view

@foreach($subcategories as $row) 
                    <td>{{$i}}</td>
                    <td>{{$row->name}}</td>  
                    <td>{{$row->categories->name}}</td>

@endforeach

I got the error like :

ErrorException in Collection.php line 1527: Property [name] does not exist on this collection instance. How do i access $row->categories->name ? anyone with the suggestion please?

Upvotes: 1

Views: 1674

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

You have to make another foreach() loop Because your subcategories belongsToMany categories. row->categories returns a collection, not an object. Thus the error.

<td>{{$row->name}}</td>  
<td>{{$row->categories->name}}</td>

@foreach($row->categories as $category)
    <td>{{$category->name}}</td>
@endforeach

Update

Getting a category with all subcategories. Simply invert your query

$category = Category::with('subcategories')
->where('name', '=', 'cars')
->first(); 
//will return you the category 'cars' with all sub categories of 'cars'. 

Without eager loading

$category = Category::find(1);
$subacategories = $category->subcategories;

return view('Subcategory::category_subcategory', compact('category', subcategories));

Upvotes: 2

Related Questions