问题
In new laravel I can't get session in constructor. Why?
public function __construct()
{
dd(Session::all()); //this is empty array
}
and then below
public function index()
{
dd(Session::all()); //here works
}
In old laravel i remember there was not this problem. something changed?
回答1:
You can't do it by default with Laravel 5.3. But when you edit you Kernel.php and change protected $middleware = []; to the following it wil work.
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
Hope this works!
回答2:
As of other answers no out of the box solution for it. But you still can access it using Middleware in constructor.
So here is another hack
public function __construct(){
//No session access from constructor work arround
$this->middleware(function ($request, $next){
$user_id = session('user_id');
return $next($request);
});
}
回答3:
In Laravel 5.3 sessions related functionality will not work in the a controller constructor, so you should move all sessions related logic to methods.
回答4:
Laravel 5.7 solution
public function __construct()
{
$this->middleware(function ($request, $next) {
// fetch session and use it in entire class with constructor
$this->cart_info = session()->get('custom_cart_information');
return $next($request);
});
}
If you want to use constructor for any other functionality or query or data then do all the work in $this->middleware function, NOT outside of this. If you do so it will not work in all the functions of entire class.
回答5:
*This one solved mine problem to use session in constructor*
$this->middleware(function ($request, $next) {
if (!session('records_per_page')) {
session(['records_per_page' => 20]);
}
// update rows per page
if (!empty(\Request::get('records_per_page')) && in_array(\Request::get('records_per_page'), [20, 50, 80, 100])) {
session(['records_per_page' => \Request::get('records_per_page')]);
}
return $next($request);
});
来源:https://stackoverflow.com/questions/41542802/laravel-cant-get-session-in-controller-constructor