Pass Data To All Views

If you need to send data to all views, to be used in your sidebar, which is part of the master template, for example, you can't do it the usual way and you will need to use a Service Provider.

Service Providers can be used to register bindings, routes, middleware or even listeners, or, as is out case, to pass data to all views.

Laravel's Service Providers are run before every request and have two methods: register and boot. We are going to need the latter for our use case.

How to send data to all views with a Service Provider

You can either use the included AppServiceProvider or create a new one. I'm going to create a new Provider to use just for passing data to views.

So first we create a file ViewServiceProvider.php in app/Providers. Service Providers always extend the class ServiceProvider.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\User; // We are going to use the User model

class ViewServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $users = User::orderBy('created_at', 'desc')->take(10)->get(); // Get the last 10 registered users
        view()->share('lastUsers', $users); // Pass the $users variable to all views
    }

    public function register()
    {

    }
}

If you decide to create a new Service Provider, like me, then you will have to register it. So head over to app/config and edit the app.php file, where you will have to add the class to the providers list.

In this case we will have to add App\Providers\ViewServiceProvider::class.

If you need to pass more variables you can use the same Service Provider.