Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sdiama's avatar

Session variables inside ExceptionHandler are not working

I'm porting an existing app into Laravel 5.2 and I'm struggling with the session management and the ExceptionHandler.

The application checks in Blade for some session variables and acting accordingly. The session variables are managed in a Middleware and the routes are inside the 'web' group. Everything works like a charm!

I'm also using a custom ExceptionHandler which checks for the error, creates custom error messages and passes them into a "generic error" view.

return response()->view('errors.generic', [
            'action'    => "error",
                'errorCode' => $e->getStatusCode(),
                'headTitle' => "Error {$e->getStatusCode()}",
                'pageTitle' => $tmpErrorMessage,
                'pageTitleDescription' => "Error {$e->getStatusCode()}"
]);

The problem is that, when an error is triggered (e.x. 404) the session has not been initialized by Laravel and the view returns a "Session store not set on request".

I manage to "solve" the problem by creating an "error" route:

Route::get('/error/', 'IndexController@error')->name('error');

and I've changed the ExceptionHandler to:

return redirect()->route('error', [
            'action'    => "error",
                'errorCode' => $e->getStatusCode(),
                'headTitle' => "Error {$e->getStatusCode()}",
                'pageTitle' => $tmpErrorMessage,
                'pageTitleDescription' => "Error {$e->getStatusCode()}"
]);

and finally inside the IndexController@error :

return view('errors.generic', [
    'action'    => "error",
        'errorCode' => $request->get('errorCode'),
        'headTitle' => $request->get('headTitle'),
        'pageTitle' => $request->get('pageTitle'),
        'pageTitleDescription' => $request->get('pageTitleDescription')
]);

This solution works fine, the session is initialized by the Laravel, and the session variables are accessible from the template. But.... this solution creates an ugly URI.

What am I doing wrong with the exception handling? What can I do to have access to the session variables inside an exception handling?

T.I.A

0 likes
8 replies
d3xt3r's avatar

If you not planning to use stateless api's move the contents of web middleware group to global middleware stack. Session will always be created then.

sdiama's avatar

Thank you premsaurav for your answer.

Let me see if I understood your answer, because I'm working with Laravel 5.2 only for 4 days and I'm not very familiar with the terminology. :(

Moving my middleware from web to $routeMiddleware, I get the same error Moving the middleware at protected $middleware I have a "Session store not set on request" error The same combination of errors I get when I move Route inside or outside the web group, or when I assign I new group to them. I have tried, also to use "Session::" instead of "$request->session" but again the error I receive it depends on the combination. On every case when an error is fired up, the middleware is not called or if It called has no session or request!

Is this what your mean, or I understood it wrongly?

Thanks you, for your time.

PS: Please keep in mind I work on 5.2 and if I understood correctly, on 5.2 they changed, how sessions are managed internally.

d3xt3r's avatar

What i meant, is that in your kernel, it should look something like, and don't use web group. You will then have access to session for each request, unless something else is screwed up.

 /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
           \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
           \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
    ];
sdiama's avatar

Thank you again premsaurav.

Unfortunately... if I move the middleware at the global stack, I get the "Session store not set on request". According Matt's blog post:

anything that's not given a web middleware will not have cookies or session or CSRF functional.

...and I cannot find in the documentation or in the web, if and how it's possible to initialize the session on my own middleware :(

d3xt3r's avatar

Unfortunately... if I move the middleware at the global stack, I get the "Session store not set on request".

Show the full error trace ?.

anything that's not given a web middleware will not have cookies or session or CSRF functional.

This is conditionally true, will explain later.

sdiama's avatar
RuntimeException in Request.php line 794:
Session store not set on request.

in Request.php line 794
at Request->session() in CheckSessionMiddleware.php line 22
at CheckSessionMiddleware->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckSessionMiddleware), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54

The line 22 contains the attempt to access the $request->session()

d3xt3r's avatar
d3xt3r
Best Answer
Level 29

What is this? CheckSessionMiddleware(), if at all using this move it below StartSession middleware.

sdiama's avatar

Hmm... You just gave me the idea!!!

CheckSessionMiddleware() is my middleware which performs the required session checks. The output of the previous message, is the error trace when the middleware is located at global stack, using Laravel's "default" way

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\CheckSessionMiddleware::class,
];

Reading your comment I decided to include \Illuminate\Session\Middleware\StartSession::class (used at web group) also at the global stack, before my middleware like this:

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\CheckSessionMiddleware::class,
];

Now the application works fine. The sessions are there to use them and the view (which uses sesssion variables) that created at the ExceptionHandler works fine. I'm not sure it's the right way but at least it works.

I believe it will be better to keep using the web group and include there the Exception class, after my middleware but I didn't find out yet what to include.

Thank you for your help ...and any other idea, is welcomed

Please or to participate in this conversation.