Wednesday, March 15, 2017

Laravel : How to access many to many relationship data

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');
        }
}

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></td>
                    <td></td>  
                    <td></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?



via User57

Advertisement