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

sitmgreg's avatar

Exception handler for PostTooLargeException

Hi there, So I've added this in the render function for app/Exceptions/Handler.php

    if ($exception instanceof PostTooLargeException) {
        return redirect('/#my_form')
            ->withInput()
            ->withErrors('Your file is too large, try exporting a smaller image');
    }

Now if I add throw new PostTooLargeExeception to my controller, my form re-populates and my error message shows up.

However, if I remove that line from the controller, and actually upload a larger than allowed file, I am redirected to the right part of my page, but no input and no error messages.

This is on an Apache server. In homestead, I simply get the nginx error page.

So I'm supposing here that the file actually being too large is losing session or something like that (?), so I'll probably just have to do a view() on a special error page with a link back to the form, unless there is a more clever solution.

0 likes
1 reply
Talinon's avatar
Talinon
Best Answer
Level 51

I had a similar issue. I wanted to be able to catch the exception and redirect back with an error message. The trouble is that the exception is rendered before the Session starts.

I worked around this by editing App/Http/Kernel.php and moving the ValidatePostSize class from the middleware array into the middlewareGroups array -- directly after the StartSession class:


    protected $middlewareGroups = [
        'web' => [

            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,

    
5 likes

Please or to participate in this conversation.