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

Poxucis's avatar

Laravel 5.3 session in constructor

Hi, so after upgrading to 5.3 problem appeared with my cart module based on session, here how it looks - http://laravel.io/bin/jQzw6

Any ideas what to change, so it will work again?

0 likes
4 replies
ABDELRHMAN's avatar

n Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet. As an alternative, you may define a Closure based middleware directly in your controller's constructor

public function __construct()
    {
    $this->middleware(function ($request, $next) {
               $this->cart = session()->has( 'cart' ) ? session()->get( 'cart.items' ) : [];

                return $next($request);
        });
}

laravel session in constructors

2 likes
Poxucis's avatar

I already did that, but i need it in my Cart class not in controller.

ABDELRHMAN's avatar

@XiaodongHe , yes , but he want to do that in a class not controller , it should work with no thing , but it's not working with him

Please or to participate in this conversation.