dsedug8644 2017-04-11 02:41
浏览 230
已采纳

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

I have a global middleware that checks if the app is in development mode, and if it is it returns a login form view, this view validates the login and then uses the errors variable to display any validation errors:

App\Http\Kernel

/**
 * 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 variable in my view

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

This worked great in Laravel 5.2, but when I updated to L5.4 the session and the error sharing gets instantiated in the web middleware group so now in L5.4 there is no access to the session in my global middleware.

/**
 * 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',
    ],
];

How do I manually instantiate a new session in my global middleware so that I can use the $errors variable for validation?

  • 写回答

1条回答 默认 最新

  • douyan2821 2017-04-12 02:15
    关注

    I found that the easiest way was to start the session and share the errors on the global middleware so that we can get access to the $errors variable in the view. If anybody recommends another solution I will change the accepted answer.

    /**
     * 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,
    ];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?