Laravel动态控制器中间件

问题描述 投票:0回答:1

嗨所以我有一些保存在数据库中的路由,每个路由都有自己的控制器及其中间件,并通过这条路由路由;

Route::get('{any}', 'RoutingController@index')->where('any', '.*');

我尝试按如下方式创建新控制器;

$container = app();
$route = $container->make(\Illuminate\Routing\Route::class);
$controllerInstance = $container->make($controller);
return (new ControllerDispatcher($container))->dispatch($route, $controllerInstance, $action);

所以我的HomeController在这里有一个中间件;

public function __construct()
{
    $this->middleware('guest');
}

然而,这并不值得尊敬,因为我猜它不是一个新的请求。有什么方法可以兑现这个中间件吗?

laravel middleware
1个回答
1
投票

控制器调度程序不是您想要的,因为中间件是控制器上方的层。您需要运行整个路线:

在你的RoutingController

public function index() {
     //Override your route with what it really needs to do
     $route = Route::get(
         {any},
         '\App\Http\Controllers\HomeController@index'
    )->where('any', '.*');
    //Re-handle the request. It should hit your new route.
    app()->make(\Illuminate\Contracts\Http\Kernel::class)->handle(request());
}

我们的想法是根据请求覆盖您需要做的事情的一般路线。这应该只影响单个请求。

© www.soinside.com 2019 - 2024. All rights reserved.