【问题标题】:Laravel Group inside Group Middleware组中间件中的 Laravel 组
【发布时间】:2015-10-22 00:33:40
【问题描述】:

我在一个组内使用中间件时遇到了一点问题,该组内部有一个中间件,如下所示:

    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 范围之外进入了最后一个中间件事件。我怎样才能避免它? 谢谢大家

【问题讨论】:

  • 你有什么问题?有什么错误吗?
  • 抱歉,更新了描述
  • 你能把你的语言中间件和你的app/Http/Kernel.php也包括进来吗?
  • 你能举一个你想要获取的网址的例子吗?
  • 我在 protected $middleware = [ .... 'App\Http\Middleware\AuthenticationMiddleware' 和 protected $routeMiddleware = [... 'authentication' => 'App\ Http\Middleware\AuthenticationMiddleware' ];

标签: laravel laravel-5 laravel-routing


【解决方案1】:

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

来自文档:

如果您希望在对您的每个 HTTP 请求期间运行中间件 应用程序,只需在 $middleware 中列出中间件类 app/Http/Kernel.php 类的属性。

和:

如果您想将中间件分配给特定的路由,您应该 首先在你的中间件中分配一个速记键 app/Http/Kernel.php 文件。默认情况下,$routeMiddleware 的属性 此类包含 Laravel 中包含的中间件的条目。 要添加您自己的,只需将其附加到此列表并为其分配一个键 您的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-09
    • 2019-10-16
    • 2022-01-11
    • 2019-08-19
    • 2018-06-28
    • 2021-11-14
    • 2015-08-17
    • 2017-09-26
    相关资源
    最近更新 更多