Database driven menu that can be loaded into view

I created a database driven menu using a controller,

HomeController extends the controller, which loads the menu into the controller constructor function.

HomeController.php

class HomeController extends Controller { public function __construct() { parent::__construct(); $this->middleware('auth'); } public function index(){ $data['menu'] = $this->menu; return view('home', $data); } } 

controller.php

 public function __construct() { $this->user = Auth::user(); $menu = new Menu(); if($this->user != NULL && $this->user != ""){ $this->menu = $menu->getMenu($this->user->user_id); } } 

How can I call a function right at the presentation level, because right now, even if the menu is loaded in the constructor, I still need to pass the menu to the view, which makes things a little redundant.

P / S: Using laravel 5.1

+5
source share
1 answer

Create a new ServiceProvider from the wizard by running the following command

 php artisan make:provider ComposerServiceProvider 

this will create a new ComposerServiceProvider.php file name in the application / Providers. In the download function of this newly created service provider, you can create functions with closure, as shown below:

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

here the view in question is navbar.blade.php in the view / partial files, which will have the named genre variable available through your application.

To make your code clean, what you can do is create a new function in ComposerServiceProvider and name it anything like, say, partialnav. Then follow these steps:

 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 the name of the application / Http, it allows you to use ViewCompoers. In this folder, create a new file called 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 go back to your partialposal function ComposerServiceProvider

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

Remember to add this newly created ServiceProvider to your config / app.php

 App\Providers\ComposerServiceProvider::class, 
+3
source

Source: https://habr.com/ru/post/1234176/


All Articles