Wells
Wells

Reputation: 142

How can i display grouped values in Laravel

I'm Trying to display restaurant Menus grouped by the categories, for example...

So I have 3 tables in my database, Restaurants, Categories, And Menus

Category Model

class Category extends Model
{
    protected $fillable = [
        'name'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
    */
    public function menus_type()
    {
        return $this->hasMany('App\Menu','category_id');
    }
}

Menu Model

class Menu extends Model
{
    protected $fillable = [
        'name',
        'price',
        'description',
        'photoPath',
        'restaurant_id',
        'category_id',
    ];

    /**
     * Menu belongs to Restaurant
     */
    public function restaurant()
    {
        return $this->belongsTo('App\Restaurant');
    }

    /**
     * Menu belongs to category type 
     */
    public function category_type()
    {
        return $this->belongsTo('App\Category', 'category_id');
    }

}

Restaurants controller

public function show($slug, RestaurantRepository $repository){
      if(! $restaurant = $repository->get(['slug' => $slug], with(['cuisines','user', 'photos', 'thumbs', 'region', 'ratings.user']))) return abort('404');

      $menus=Menu::with(['category_type'])->where('restaurant_id',$restaurant->id)->get()->groupBy('category_id');

       return view('frontend.restaurant.show', compact('restaurant', 'p','menus'));
}

when i Dump this it looks just fine.

This is what is returned from the $menu variable

Results have been grouped

Expand results set with relationships

Now my trouble is on the View when i try to get results of this i get an error.

   @if($menus)
   <ul>
     @foreach($menus as $m)
       <li>
         {{$m->name}}
       </li>
     @endforeach
   </ul>
   @endif

ErrorException (E_ERROR).

Property [name] does not exist on this collection instance.

Upvotes: 2

Views: 568

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Iterate inner loop also. 'groupBy()' creates another array with category_id as key.

@if($menus)
 <ul>
 @foreach($menus as $category_id=>$outer)
  @foreach($outer as $k=>$inner)
   <li>
      {{$category_id}}: {{$inner->name}}
   </li>
   @endforeach
 @endforeach
 </ul>
 @endif

Updated you query to get from category

$categories = Category::with('menus_type')->get();
return view('frontend.restaurant.show', compact('restaurant', 'p','categories '));

In your view

@if($categories ?? false)
 <ul>
 @foreach($categories ?? [] as $cat_key=>$category)
  <li>
      {{$category->name}}
  </li>
  <li>
  <ul>
  @foreach($category->menus_type as $menu_key=>$menu)
  <li>
      {{$menu->name}}
  </li> 
  @endforeach
  </ul>
  </li>
 @endforeach
 </ul>
 @endif

Upvotes: 1

Related Questions