Skip to content
Advertisement

How do i load my dynamic menu item on every page in Laravel?

Is there way to load my menu categories and sub-categories(which is fetched from database) on every page? What I was doing was

$categories = $this->someService->getAllCategories();
return view('some-view',compact('categories'));

on every view that I was returning from a controller. Is there a good way to handle such situation ?

Advertisement

Answer

Using View Composers you can pass data to a view every time it is used.

You should outsource the html that uses the categories into its own partial, then in your ServiceProvider:

View::composer('some-view-partial', function ($view) {
    return $this->someService->getAllCategories();
});

And yes, a database call on every pageload does affect your page load time. But a view composer is the best approach to get the data every time (and the view composer itself won’t affect your loading time, the thing that happens inside it affect it).

Consider storing your categories in your Application Cache if they don’t change that often so that you don’t hit your database that often.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement