How can get the session value on the controller constructor in the laravel
Today, I am going to share with you how can get the session value in the controller constructor in laravel. something many people says sometimes we cannot be getting the value of the session in laravel controller constructor but we can get and use session value easily value in another method. so why are we cannot get data directly in the controller constructor because the session middleware has not run yet which returns a blank?
we can not get the session value in below Following the Controller constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ProductController extends Controller { public function __construct() { dd(Session::all()); //Return The empty array } public function index() { echo "<pre>"; print_r(Session::all()); //It's works echo "</pre>"; die; } } ?> |
You put below following code in constructor after you can easily get session value in the constructor.
1 2 3 4 5 6 7 8 9 | public function __construct() { $this->middleware(function ($request, $next) { if(Session::get("logged_in") == false && empty(Session::get('logged_in'))) { Redirect::to('admin/login')->send(); } return $next($request); }); } |
But you can also some changes and use the following code in protected $middleware = [] on “app/Http/kernel.php” file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ \App\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, \App\Http\Middleware\TrustProxies::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; |
Please follow and like us: