2

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.

tgrass
  • 135
  • 3
  • 12

2 Answers2

4

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 = [...].

Flame
  • 6,663
  • 3
  • 33
  • 53
  • Thank you - read up on both now. Can you clarify: "should use middleware and define it that way." In AppServiceProvider I have added the following to the boot(): `$profile=session('profile'); View::share('profile', $profile);` and I have registered a global middleware for all requests - but I am unclear on what I should define and how in the ServiceProvider. – tgrass Mar 15 '19 at 01:38
  • 1
    ive edited the answer and added a middleware example – Flame Mar 15 '19 at 10:12
1

the correct way to do it is using this sentence session()->get('profile'), for example in a view {{ session()->get('profile') }}.

  • Thank you - correct, that returns the session data within the blade. I'd like to set the session('profile') as a global variable `$profile` before the blades are run so that within the blade, a developer can easily use `$profile` instead of the more verbose `session(...)` – tgrass Mar 14 '19 at 17:41