Laravel 组内组中间件

Laravel Group inside Group Middleware

我在组中使用中间件时遇到了一些问题,该组本身具有如下代码的中间件:

    Route::group(['prefix' => '{lang?}','middleware'=>'language'], function() {
        Route::get('/', 'HomeController@index');
        Route::get('/login','AuthController@login');
        Route::post('/login','AuthController@do_login');
        Route::get('/logout','AuthController@logout');
        Route::group(['prefix' => 'checkout','middleware'=>'authentication'], function () {
           Route::get('/', "CheckoutController@step1");
    });
});

还有我当前的 AuthenticationMiddleware

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\Middleware;
use Session;
use App;
use Redirect;
class AuthenticationMiddleware{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        die("inside");
        if(!User::check())
        {
            return Redirect::to("/login");
        }
        else
        {
            return $next($request);
        }
    }

}

编辑: 因此,他在 /checkout 范围之外进入了最后一个中间件事件。我怎样才能避免呢? 谢谢大家

根据您的评论,我看到您在 $middleware$routeMiddleware 上都添加了中间件,因此 AuthenticationMiddleware 将在每个请求上 运行。如果您只希望您的请求在您指定的路线上通过 AuthenticationMiddleware,则将其从 $middleware 中删除并仅将其保留在 $routeMiddleware.

来自文档:

If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

和:

If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing.