简体   繁体   English

Laravel中间件不会在每个请求之前运行

[英]Laravel middleware won't run before every request

I have this simple middleware 我有这个简单的中间件

<?php

namespace App\Http\Middleware;

use Closure;
use Session;
use App;

class SetPageLanguage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if(Session::has('language'))
        {
            $lang = Session::get('language');

            App::setLocale($lang); // still don't know which one to use, but I'll figure it out ;)
            app()->setLocale($lang);
        }

        return $next($request);
    }
}

Which is supposed to run before every single request. 应该在每个请求之前运行。 So I added it to the kernel: 所以我将其添加到内核中:

class Kernel extends HttpKernel
{

    protected $middleware = [

        ...

        \App\Http\Middleware\SetPageLanguage::class, // middleware for setting the language when loading a page
    ];

But it doesn't work. 但这是行不通的。 It never runs. 它永远不会运行。

On the other hand, if I put it in routeMiddleware, like so: 另一方面,如果我将其放在routeMiddleware中,则如下所示:

 protected $routeMiddleware = [

        ...

        'localization' => \App\Http\Middleware\SetPageLanguage::class,

        ...

And call it on every route, like, for example: 并在每条路线上都调用它,例如:

Route::GET('/', 'AnonymController@home')->middleware('localization');

It works perfectly! 它完美地工作! But I don't want to have to do that. 但我不想这样做。 I want it to run automatically before every single request, like it is supposed to. 我希望它像预期的那样在每个请求之前自动运行。 What am I missing? 我想念什么?

I'm quite new to laravel and Php, so I'm sure I'm not understandig something important. 我对laravel和Php很陌生,所以我确定我不了解重要的东西。

I watched some tutorials, read a few articles and searched for the answer here on Stack Overflow. 我看了一些教程,阅读了几篇文章,并在Stack Overflow上搜索了答案。 Still can't figure it out. 仍然无法弄清楚。

How can I make my middleware run before every single request? 如何让我的中间件在每个请求之前运行?

Thank you. 谢谢。

It likely is running, but global middleware run before route middleware. 它可能正在运行,但是全局中间件在路由中间件之前运行。 It's important to understand what the other middleware are doing and the order they are called. 了解其他中间件在做什么以及它们被调用的顺序很重要。

If you look at the 'web' middleware group, you'll see this middleware: 如果您查看'web'中间件组,则会看到以下中间件:

\Illuminate\Session\Middleware\StartSession::class,

Sessions are not instantly available in a Laravel app. 在Laravel应用中无法立即使用会话。 The StartSession middleware is what starts sessions for web routes. StartSession中间件是启动Web路由会话的工具。 API routes don't use sessions because they are stateless. API路由不使用会话,因为它们是无状态的。

Therefore, this middleware likely belongs in the web group below the session middlewares since it relies on session data. 因此,此中间件可能依赖于会话数据,因此可能属于会话中间件下方的Web组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM