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.

<?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.


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.

	/**
     * 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',
        ],
    ];