Intercept Laravel Routing

大兔子大兔子 提交于 2019-12-04 17:20:20

I think Middleware might not be the best place to do that. You have access to the route, but it doesn't offer a away to modify the controller method that will be called.

Easier option is to register a custom route dispatcher that handling the logic of calling controller methods based on the request and the route. It could look like that:

<?php

class VersionedRouteDispatcher extends Illuminate\Routing\ControllerDispatcher {
  public function dispatch(Route $route, Request $request, $controller, $method)
  {
    $version = $request->headers->get('version', 'v1'); // take version from the header
    $method = sprintf('%s_%s', $method, $version); // create target method name
    return parent::dispatch($route, $request, $controller, $method); // run parent logic with altered method name
  }
}

Once you have this custom dispatcher, register it in your AppServiceProvider:

public function register() {
  $this->app->singleton('illuminate.route.dispatcher', VersionedRouteDispatcher::class);
}

This way you'll overwrite the default route dispatcher with your own one that will suffix controller method names with the version taken from request header.

Sort of a gross alternative is to create symlinks in your public folder that point back to the public folder. Use middleware to read the url and set a global config that can be used in your controllers to determine what to show. Not ideal but it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!