mercredi 25 septembre 2019

How to get related laravel model of a related model

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 restaurants its 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>
                         
                         <ul>
                            @foreach($category->menus_type as $menu_key=>$menu)
                            <li>
                                
                            </li> 
                            @endforeach
                        </ul>
                     </li>
                     @endif


                    @endforeach
                    </ul>
                    @endif

this is not working



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire