Laravel Blade Templates Sharing data to all views


Example

Sometimes you need to set the same data in many of your views.

Using View::share

// "View" is the View Facade
View::share('shareddata', $data);

After this, the contents of $data will be available in all views under the name $shareddata.

View::share is typically called in a service provider, or perhaps in the constructor of a controller, so the data will be shared in views returned by that controller only.

Using View::composer

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location. You can directly bind variable to a specific view or to all views.

Closure-based composer

use Illuminate\Support\Facades\View;

// ...

View::composer('*', function ($view) {
    $view->with('somedata', $data);
});

Class-based composer

use Illuminate\Support\Facades\View;

// ...

View::composer('*', 'App\Http\ViewComposers\SomeComposer');

As with View::share, it's best to register the composers in a service provider.

If going with the composer class approach, then you would have App/Http/ViewComposers/SomeComposer.php with:

use Illuminate\Contracts\View\View;

class SomeComposer
{
    public function compose(View $view)
    {
        $view->with('somedata', $data);
    }
}

These examples use '*' in the composer registration. This parameter is a string that matches the view names for which to register the composer (* being a wildcard). You can also select a single view (e.g. 'home') of a group of routes under a subfolder (e.g. 'users.*').