在 Laravel 5.5 中处理 PostTooLargeException

Handling PostTooLargeException in Laravel 5.5

我正在尝试在我的 Laravel 5.5 应用程序中处理 PostTooLargeException

当我尝试通过我的表单上传太大的文件时,我收到了 PostTooLargeException,我在 app\Exceptions\Handler.php 中成功捕获了它,但是在这一步我想将用户重定向回带有表单的页面并显示一条错误消息。

我写了下面的代码:

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');
            }
    ...
    }
}

结果我被重定向到正确的页面但没有任何消息并且 ViewErrorBag 是空的。 我的重定向有问题吗?

谢谢大家帮忙!

ViewErrorBag 为空,因为会话未在 Handler 中启动。 @Talinon at Laracast

之前描述了解决方案

为了使会话在 Handler class 中可用,我将 \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class$middleware 移动到 $middlewareGroups 数组 App/Http/Kernel.php

我更新后的 $middlewareGroups 数组如下所示:

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,

        ],
        ...
];