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

Scott's avatar

Flashing session data from exception handler

Hi, can someone help me figure out how to flash session data from an exception handler in Laravel 5? Here is where I'm stuck...

This is my exeption handler located in ErrorServiceProvider.php

$handler->error(function(\SampleException $e) use ($log)
{
    \Session::flash('foo', 'bar');
    return \Redirect::to('sandbox');
});

And here are my routes

// Just dump the session data
$router->get('sandbox', function() {
    var_dump (Session::all());
});

$router->get('flash', function() {
    \Session::flash('hello', 'world');
    return \Redirect::to('sandbox');
});

$router->get('exception', function() {
    throw new \SampleException;
});

What has me confused is if I hit the 'flash' route, the session data works. Yet when I dump the session data after hitting the 'exception' route, which has the same code in the handler, the session data is empty. Does anyone know what I'm missing here?

0 likes
5 replies
Valorin's avatar

Try using the with function on the redirect:

Redirect::to('sandbox')->with('foo', 'bar');
Scott's avatar

This method only seems to work when I redirect this way from the routes file. When doing it from the exception handler, the session data is not passed.

Valorin's avatar

Ah, it's possible the exception handler doesn't have the session initiated properly, so the flash data can't be saved.

Try using a URL parameter and passing a keyword, so you redirect to a path like: /sandbox?hello=world.

This will ensure the param is passed, and you just need to grab it via Input::get('hello') and deal with it manually.

Scott's avatar

I'd prefer not to do it with regular get variables, it needs to be sessions. Do you know of any work around I might be able to use to set session variables before throwing an exception with a redirect?

Valorin's avatar

I'm not that familiar with the internals of sessions and the exception handler. Do you need to redirect from the exception? Can you simply return a view from the exception handler, and do your work in there directly?

Or possibly redirect to a custom url for the specific message you'd pass via session?

What about redirecting to a url with variables, and having that store in session and redirecting to a clean url? It's not pretty, but it might work.

Final crazy idea: Store the data in a special case value, and check for it when you check session. Would only work if your user is logged in, so you can ID them, but might do the trick.

Please or to participate in this conversation.