Laravel 5.4访问全局中间件中的$ errors变量

时间:2017-04-11 02:41:51

标签: php laravel

我有一个全局中间件,用于检查应用程序是否处于开发模式,如果是,则返回登录表单视图,此视图验证登录,然后使用errors变量显示任何验证错误:

应用\ HTTP \内核

/**
 * The application's global HTTP middleware stack.
 *
 * @var array
 */
protected $middleware = [
    \App\Http\Middleware\CheckForDevelopmentMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
我视图中的

$ errors变量

{!! $errors->first('email', '<span class="help-block">:message</span>') !!}

这在Laravel 5.2中运行得很好,但是当我更新到L5.4时,会话和错误共享在Web中间件组中实例化,所以现在在L5.4中,我的全局中间件中无法访问会话。 / p>

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

如何在全局中间件中手动实例化新会话,以便我可以使用$ errors变量进行验证?

1 个答案:

答案 0 :(得分:1)

我发现最简单的方法是启动会话并在全局中间件上共享错误,以便我们可以访问视图中的$ errors变量。如果有人推荐另一种解决方案,我会改变接受的答案。

/**
 * The application's global HTTP middleware stack.
 *
 * @var array
 */
protected $middleware = [
    // Start the session and share errors globally so that we can access the
    // errors variable in the development mode view.
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\CheckForDevelopmentMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];