Ad

Fetch Records With Its Pivot Table By Laravel BelongsToMany

- 1 answer

I have categories and menu table. Each menu has many categories and each category has many menus. I have a category_menu pivot table, and now I want to fetch all menu records with its categories some thing like that.

Model:

class menu extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
}

Controller:

class homeController extends Controller
{

    public function __construct(Menu $menu, Category $category)
    {
        $this->menu     = $menu;
        $this->category = $category;
    }

    public function index()
    {
        $data['categories'] = $this->category->all();
        $data['menus']      = $this->menu->all()->categories;
        return view('home', $data);
    }
}
Ad

Answer

actually i got the answer with a lucky try it's

$this->menu->with('categories')->get();

to any one gets into this issue

Ad
source: stackoverflow.com
Ad