How to pass dynamic data to all views in Laravel

|
| By Webner

laravel dynamic data

ISSUE:

Sometimes there is a requirement, in which we need to show some dynamic data in the sidebar of every view.

SOLUTIONS:

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 –

  1. 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.

  2. The ComposerServiceProvider class is added to config/app.php array for providers that make Laravel able to identify it.
    public function boot()
    {
    view()->composer(
    *,
    'App\Http\Composers\SampleComposer'
    );
    }
  3. 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.

    <?php
    namespace App\Http\Composers;
    use Illuminate\View\View;
    class SampleComposer
    {
    /**
    * Bind data to the view.
    *
    * @param View $view
    * @return void
    */
    public function compose(View $view)
    {
    $sample_data=[
    'Foo',
    'Bar',
    'Baz'
    ];
    $view->with('sample_data', $sample_data);
    }
    }

    The compose method will bind the sample_data to every app view.

Leave a Reply

Your email address will not be published. Required fields are marked *