Sometimes there is a requirement, in which we need to show some dynamic data in the sidebar of every view.
The above scenario can be achieved using various techniques in Laravel, which are listed below –
- We can pass the sample data array on every method of controllers. This approach is not so good because in this approach we have to repeat the code on every controller.
- We can create a new service provider and register it. We can put the sample data array in the service provider boot method. This approach becomes inefficient soon when we share large datasets.
- We can take advantage of View composers. The approach of using View Composers is much more efficient than the other ways and recommended by Laravel.
Here are the steps for passing dynamic data in all views using View Composers –
- To organize the Laravel structure, we need to create a directory Composers under the directory app/Http. We need a provider to handle all our views composers. To create a provider, run the following command:
php artisan make:provider ComposerServiceProvider
The service provider will be visible under the app/Providers.
- The ComposerServiceProvider class is added to config/app.php array for providers that make Laravel able to identify it.
public function boot()
- Laravel can execute a SampleComposer@compose method every time when a view file is executed i.e. data will pass to every blade file. So, here we need to create a SampleComposer file under app\Http\Composers.
* Bind data to the view.
* @param View $view
* @return void
public function compose(View $view)
The compose method will bind the sample_data to every app view.