Laravel

Database driven menu that can be loaded in view

The problem : I have created a database driven menu using a Controller. How can I, call the function straight at the view level because right now, even though the menu is loaded in the constructor, I will still need to pass the menu to the view which makes things a bit redundant.

Solution :

Generate a new ServiceProvider from artisan by following command

php artisan make:provider ComposerServiceProvider

this will create a new file name ComposerServiceProvider.php under app/Providers. In the boot function of this newly created service provider you can create functions with closure like following :

view()->composer('partials.navbar', function ($view) {
        $view->with('genre', Genre::all());
    });

here the view in question is navbar.blade.php under view/partials which will have a variable named genre available through out your app.

To make your code cleaner what you can do is create a new function in the ComposerServiceProvider and name it anything lets say partialnav. Then will do the following :

public function boot()
{
    $this->partialNav();
}

//create a function independently

public function partialnav()
{
    //code goes here
}

If you want to separate it even more you can create a new folder under app/Http name it lets say ViewCompoers, Under this folder create a new file named NavbarComposer.php with the following code :

class NavbarComposer {


/**
 * Create a new profile composer.
 *
 * @param  UserRepository  $users
 * @return void
 */
public function __construct()
{
    // Dependencies automatically resolved by service container...
}

/**
 * Bind data to the view.
 *
 * @param  View  $view
 * @return void
 */
public function compose(View $view)
{
    //write your code to fetch the data 
    // and pass it to your views, following is an example
    $genre = genre::all();
    $view->with('genre', $genre);
}
}

now back to your ComposerServiceProvider’s partialnav function

public function partialNav()
{
    view()->composer('partials.nav', 'App\Http\ViewComposers\NavbarComposer');
}

Don’t forget to add this newly created ServiceProvider in your config/app.php

App\Providers\ComposerServiceProvider::class,