-2

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

3 Answers3

0

Place this in your __construct() function of your controller that will handle the request.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • i did that , but i'm not sure where to assign my global variables, i tried to access it from within and it did get the session data , so i guess assignment is inside of the closure func. – Shaker Younis Jan 16 '17 at 08:49
  • Closure's are scoped, you must use($var)` in order to have it scoped correctly. – Ohgodwhy Jan 16 '17 at 08:58
0

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.

Loek
  • 4,037
  • 19
  • 35
  • well , im trying to initialize a global variable with user data inside the constructor , else i have to recall it from the database – Shaker Younis Jan 16 '17 at 08:44
  • Create a middleware for that and add it to the necessary routes then. Constructors are for initializing properties of that class and nothing more. – Loek Jan 16 '17 at 08:46
0
 public function __constrcut(){
    //changing language accordding to session
    $this->middleware(function($request,$next){
        app::setLocale(Session::get('locale'));
        return $next($request);
    });

This code used for changing language according to session the version which i use laravel 5.5 Note: you must call the middelware first then use session as the constructor not see session this works for me

Ahmed Mahmoud
  • 1,724
  • 1
  • 17
  • 21