davidinho
davidinho

Reputation: 169

Passing data from controller to master view

I'm using Laravel and I've a large amount of index.blade.php pages that extends a master.blade.php page, now the master need some data like the list of menu items.

When I want to see the list of Aircraft I've this route:

Route::get('aircrafts', 'AircraftsController@index');

and this is the method AircraftsController@index:

public function index(){
    $aircrafts = Aircraft::all();
    $menus = Menu::all();
    return view('aircrafts.index', compact('menus', 'aircrafts'));
}

How you can see I must to pass $menus to each view in each controller, and if in some moment the master require some other data I'm forced to edit every single controller...

Is there some more smart way to pass data to the master?

I would like to avoid to retrieve the interested data directly inside the view...

Upvotes: 1

Views: 484

Answers (2)

jigs_
jigs_

Reputation: 286

If data requires in all views then you can try view()->share('menus', Menu::all()) in service provider, Otherwise View::composer() is right option for this.

Upvotes: 0

Ali Özen
Ali Özen

Reputation: 1609

in your AppServiceProvider add use View;

public function boot()
{
  View::composer('*', function($view){
    $view->with('aircrafts', Aircraft::all());
    $view->with('menus', Menu::all());
});
}

after that usage is same. Like @foreach($menus as $foo)

Upvotes: 2

Related Questions