0
votes

I'm making Restaurant menus where each restaurant has its own menu items and these menu item belong to a category(e.g breakfast, Lunch ...)

My goal is when you visit a particular restaurant it should on show the categories that are linked to the menu items with the menus in there grouped like this.

  1. Breakfast
    • Tea and Cake - $10
    • Coffee and bread - $15
  2. Lunch
    • Rice and Chicken - $45
    • Chicken and Chips - $30

My relationship is as follows...

1 Restaurant has many Menus | each Menu_Category has many Menus

in my Models I have

Restaurant model

public function menus()
{
    return $this->hasMany('App\Menu');
}

Menu model

public function restaurant()
{
    return $this->belongsTo('App\Restaurant');
}


public function category_type()
{
    return $this->belongsTo('App\Category', 'category_id');
}

Category model

public function menus_type()
{
    return $this->hasMany('App\Menu','category_id');
}

So, when I visit a particular restaurant it's should only display the categories related to the Restaurants menu items.

Restaurant controller

public function show($slug, RestaurantRepository $repository)
{


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


    $categories = Category::with('menus_type')->get(); /* This is where I'm lost */

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

frontend.restaurant.show

@if($categories)
    <ul>
      @foreach($categories ?? [] as $cat_key=>$category)

          @if($category->id ===$restaurant->menus->id)
          <li>
              {{$category->name}}
              <ul>
                  @foreach($category->menus_type as $menu_key=>$menu)
                  <li>{{$menu->name}}</li> 
                  @endforeach
              </ul>
           </li>
          @endif

     @endforeach
    </ul>
@endif

It's not working!

1

1 Answers

0
votes

Keep it simple in RestaurantController. Find out all related menu items and group them by category. Below codes are not tested though, you can give it a try.

$restaurant = Restaurant::findOrFail(1);
$categories = $restaurant->menus->groupBy('category_id');

Now, extract them on view file

@foreach($categories as $key => $category)
    {{ Category::query()->find($key)->name }}
    <ul>
        @foreach($category as $menu)
            <li>{{ $menu->name }}</li>
        @endforeach
    </ul>
@endforeach