Tuesday, April 11, 2017

Laravel 5.4 access $errors variable in global middleware

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?



via enriqg9

Advertisement