laravellaravel-eventslaravel-session

How do I create a Laravel global variable from session data and make available across all views?


I set session data on login in the LoginController like so:

class LoginController extends Controller{
    protected function authenticated($request, $user){
       $record = ['name'=>'bob'];
       session(['profile' => $record]);
    }
}

The session is available in any blade:

$profile = session('profile');

How do I have the variable $profile available on all blades?

I have tried using Event Listeners and View::share( 'profile', session('profile')) but the session data does not seem to be accessible yet in the Events I have used.


Solution

  • What you're looking for are view composers:

    https://laravel.com/docs/5.8/views#view-composers

    If your session data is not available in the boot process of the Service Providers (which it isn't), you should use middleware and define it that way:

    https://laravel.com/docs/5.8/middleware#registering-middleware

    // App\Http\Middleware\MyMiddleware.php
    class MyMiddleware
    {
        public function handle($request, Closure $next, $guard = null)
        {
            $profile = session('profile');
            View::share('profile', $profile);
    
    
            // Important: return using this closure,
            // since this is all part of a chain of middleware executions.
            return $next($request);
        }
    }
    

    Next make sure your middleware is loaded in App\Http\Kernel.php (for instance on the global middleware stack protected $middleware = [...].