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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?