Handling PostTooLargeException in Laravel 5.5

假装没事ソ 提交于 2019-12-11 11:57:12

问题


I am trying to handle PostTooLargeException in my Laravel 5.5 application.

When I trying to upload too big file through my form I receive PostTooLargeException which I successfully catch in app\Exceptions\Handler.php, but on that step I would like to redirect user back to the page with form and show an error message.

I wrote following code:

class Handler extends ExceptionHandler
{
...
    public function render($request, Exception $exception)
    {
    ...
        if($exception instanceof PostTooLargeException){
                    return redirect()->back()->withErrors("Size of attached file should be less ".ini_get("upload_max_filesize")."B", 'addNote');
            }
    ...
    }
}

As a result I was redirected to the proper page but without any message and ViewErrorBag was empty. Did I something wrong with that redirection?

Thank you a help!


回答1:


The ViewErrorBag is empty because session is not start in the Handler. Solution was previously described by @Talinon at Laracast

To make session available in the Handler class, I moved \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class from $middleware to $middlewareGroups array at the App/Http/Kernel.php

My updated $middlewareGroups array looks like:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, // <<< this line was added
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,

        ],
        ...
];


来源:https://stackoverflow.com/questions/49650234/handling-posttoolargeexception-in-laravel-5-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!