Search code examples
phplaravelsessionlaravel-5.3laravel-middleware

Explain how to use Session In The Constructor Laravel 5.3


according to laravel docs https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors i can no longer access the session in the construct because the middleware isnt loaded yet , they provided an example that i couldnt understand

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->projects = Auth::user()->projects;

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

how do i access my session here inside that function? , an explaination would do


Solution

  • The Laravel docs state that you can't access middleware anymore in the constructor, because it hasn't been loaded yet.

    By using that specific Closure, you're actually forcing php (and Laravel) to load whatever logic you have in the Closure as middleware. Take a look at the basic controller class provided by Laravel and see if you can connect the dots.

    Essentially, you're hacking the framework.

    That being said, it's really bad practice and you shouldn't temper with your session in controller's constructors.