Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CharlesK's avatar

Laravel pass session variable to the middleware

Hello

Currently I was trying to share a variable which uses Session ID like so.

$currentSessionID = session()->getId();
$inCartDetails = Cart::where('session_id', $currentSessionID)->get();
View::share('inCartDetails', $inCartDetails);

I had placed this in the boot of AppServiceProvider but it did not work because "session data is not accessible in the app boot process, You should use middleware like Taylor Otwell said in Add event for session started conversation".

I followed as it says and created a middleware called CommonData

public function handle($request, Closure $next)
{
    $currentSessionID = session()->getId();
    $inCartDetails = Cart::where('session_id', $currentSessionID)->get();
    View::share('inCartDetails', $inCartDetails);
    // return $next($request);
}

How would I use this variable from the middeware in a header that is globally on all my views? The header in itself doesn't have a controller since it's included in the master blade. Any ideas?

0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@charlesk

Why not store $inCartDetails in a variable session using the session() helper?

To set a variable session :

session(['inCartDetails' => $inCartDetails]);

To retrieve the variable session anywhere in your project (routes, controllers and views) :

echo session('inCartDetails'); // or {{ session('inCartDetails') }} for blade views
2 likes

Please or to participate in this conversation.