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

Michael__'s avatar

[BUG?] Flash Messages not working in exception handler

Hey,

Update: Newest question at: https://laracasts.com/discuss/channels/general-discussion/flash-messages-not-working-in-exception-handler/replies/48784

I have a problem with using flash messages in the main exception handler (inside the render method).

Current code:

        if($e instanceof UserBannedException) {
            $banReason = $e->getMessage();
            if(!empty($banReason)) {
                return redirect('auth/signin')->withErrors([trans('error.user_banned_for_reason', ['reason' => $banReason])]);
            }

            return redirect('auth/signin')->withErrors([trans('error.user_banned')]);
        }

It does correctly redirect, but it does NOT display the message for some reason. Messages from validation errors are displayed though.

Any idea what the problem is? Can't find it.

Thank you very much!

0 likes
37 replies
bobbybouwmann's avatar

It's working fine for me! How do you show your errors in your view?

bobbybouwmann's avatar

It's working fine for me! How do you show your errors in your view?

usman's avatar

@Gewora you can use either of the following to retrieve the error inside view:

$errors->first();

or

app('session')->get('errors')->first();
Michael__'s avatar

@blackbird That is really strange.

The errors are retrieved with the following:

@foreach($errors->all() as $error)
    <p class="alert alert-danger">{{$error}}</p>
@endforeach

Shouldn't that be fine? As said, it works fine with validation errors (server sided).

Thanks

Michael__'s avatar

If I do a

{{ dd($errors->all()) }} 

in the view, it shows an empty array :( Seems like something is removing it from the session. No idea what though.

Michael__'s avatar

It is driving me nuts. I try to debug it, but it is really hard. If I dump it right after flashing it (without something between) then it shows the flashed message in the session. If I dump it in the main Controller (inside the constructor) after the redirect it does not show it anymore. What is between those that could cause this problem? I even disabled all custom middleware, still the same problem.

pmall's avatar

Hum you should show more code here. Show what throws UserBannedException.

Michael__'s avatar

What do you mean by that? It is just an Exception that is thrown when the user that tries to authenticate is banned. Nothing special. I do not think that this is related to the problem in any way. It is correct catched, the flash messages are the problem.

Thanks

pmall's avatar

I just suggested you show some code if you want us to take a look at your problem. Obviously something don't work and we can't guess.

Michael__'s avatar

Yeah, but no clue which code. The exception clearly is not the problem as it is catched correctly. That is why I tried to explain it as best as possible 2 posts above. It looks like it is something between the flashing and the controller of the new request. Can't find out what..

pmall's avatar

Something else must be wrong. Is the exception thrown from a controller action or a middleware ?

For example I had trouble with session in a service provider because the session mechanism is set by a middleware which run after the service providers.

i mean your data can be in the flash array of the session but maybe the bug is the session is not saved properly.

Michael__'s avatar

The exception gets thrown inside a repository.

pmall's avatar

Please show the whole code related to your bug if you want help.

Michael__'s avatar

It is basically like that: UserController calls the validation method on the UserRepository. The UserRepository throws the UserBannedException.

Michael__'s avatar

@pmall Even though if I am almost sure that the code won't help, there we go:

DbUserRepository:

<?php namespace App\Repositories;

use Illuminate\Support\Facades\Auth;
use App\Interfaces\UserRepositoryInterface;
use App\Exceptions\User\UserBannedException;

class DbUserRepository implements UserRepositoryInterface
{
    public function validate($username, $password)
    {
        # Use the Auth method to check the
        # submitted credentials
        $validate = Auth::attempt(compact('username', 'password'));

        if($validate === true) {
            # Check if the user has been banned
            if(!is_null(Auth::user()->banned)) {
                throw new UserBannedException;
            }

            # The user has been successfully authenticated
            return true;
        }

        # Unable to authenticate the user
        return false;
    }
}

AuthController:

class AuthController extends Controller
{
    public function __construct(UserRepositoryInterface $user)
    {
        $this->user = $user;
    }
    public function postSignin(SignInRequest $request)
    {
        $username = Request::input('username');
        $password = Request::input('password');

        # Validate the entered credentials
        $validate = $this->user->validate($username, $password);

        if($validate === false) {
            return redirect()->back()->withErrors(['Please check your login credentials and try again!']);
        }
    }
 }
sitesense's avatar

Not sure but maybe:

if($validate === true) {
            # Check if the user has been banned
            if(!is_null(Auth::user()->banned)) {
                throw new UserBannedException;
            } else {

                # The user has been successfully authenticated
                return true;
            }
Michael__'s avatar

@sitesense I can't really follow you. Can you explain your thoughts? The exception is thrown and catched correctly, so why should that do something at all?

Thank you!

sitesense's avatar

Was looking at what you said here:

but does NOT display the message for some reason. Messages from validation errors are displayed though.

Does that mean validation errors are displayed 'instead' of exception error?

I was thinking perhaps your redirect in the controller was overriding the flash message from the exception, but after taking another look, I don't think that could be the case.

Sorry, my mistake.

Michael__'s avatar

No, I meant if i force a validation error it will show up. Just pointed that out to clearify that the messages are technically displayed correctly. Thanks though!

Michael__'s avatar

I just tried to do the redirect with the error message instead of throwing an exception, that works. I hope that this is of any help to find the issue.

Michael__'s avatar

Alright the last thing that I just found out:

If I catch the Exception in the AuthController like that:

        try {
            $validate = $this->user->validate($username, $password);

        } catch(UserBannedException $e) {
            return redirect('auth/signin')->withErrors([trans('error.user_banned')]);
        }

it works fine. So what does happen between the Controller and the global exception handler? For someone who understands what is going on behind the scene there should now be a very limited pool of possible reasons.

pmall's avatar

Maybe the global exception handler is run after the session data are actually written to the session storage ??

Anyway, your solution in your last post seems fine as this is not a global exception. I guess you won't use this exception in any other part of your code.

pmall's avatar

Is the code catching the exception is in the report or render method of the exception handler ?

Michael__'s avatar

It does not look like that. I handle another exception in the handler and it works. There seems to be an issue between the Controller and the exception handler.

Sadly this exception can be throws and multiple places, so I do indeed need it in the global exception handler.

Update: It is in the render method. It works fine for another exception, so this can not be the issue.

pmall's avatar

I handle another exception in the handler and it works.

Another exception adding data to the session ??

Michael__'s avatar

Okay, there is for sure a problem with throwing the exception in the repository. If I go ahead and throw it in the AuthController it works fine (catched by the global handler). But it seems to be that it has problems when it goes like that: Repository->Controller->ExceptionHandler

But why? Not sure if this is a bug?

Update: Sorry for marking you @JeffreyWay but it does not look like that anyone else is able to find out what is causing this. Do you have any idea why this is happening?

Thanks for any help

pmall's avatar

@Gewora it works perfectly fine at my place.

# in routes.php
class TestException extends \Exception{}

$router->get('test', function(){ throw new TestException(); });
# error handler
public function render($request, Exception $e)
{
    if ($e instanceof \TestException)
    {
        return redirect()->route('targets.create')->withErrors(['test']);
    }

    return parent::render($request, $e);
}

When visiting /test im redirected and the error is shown.

Michael__'s avatar

@pmall Don't get me wrong but you need to read my post more carefully. What you did works fine for me too, that did not reproduce the issue.

Next

Please or to participate in this conversation.