【问题标题】:Laravel check if route uses macroLaravel 检查路由是否使用宏
【发布时间】:2019-07-03 00:54:54
【问题描述】:

无法确定哪些路由使用宏。

我在我的应用服务提供商中注册了一个宏,并在一些路由上使用了它。我想看看哪些路由使用了这个注册的宏。当我在任何路由上调用 hasMacro 时,无论路由是否使用它,它都会在所有路由上返回 true。

它在文档中说如果宏已注册,则 hasMacro 方法返回 true,这解释了为什么所有路由都返回 true。

文档:https://laravel.com/api/5.6/Illuminate/Routing/Route.html

有没有办法确定路由是否使用自定义宏?我很乐意在调用此宏时更改组、命名空间或中间件,然后进行查询,但到目前为止还无法做到。有什么建议吗?

Route::macro('graphQL', function ($type = 'query', $isList = true) {
            if (!in_array($type, ['query', 'mutation'])) throw new InvalidGraphQLTypeException();

            // throw new GraphQLControllerMethodException("This route is for a GraphQL endpoint and can not be accessed.");
        });
$graphQlRoutes = collect(Router::getRoutes())->filter(function($route) {
            /** @var Route $route */
            return $route->hasMacro('graphQL');
        });

【问题讨论】:

    标签: laravel routes router


    【解决方案1】:

    啊哈!轻松解决。在宏内部只需设置一个属性,然后检查它。

    Route::macro('graphQL', function ($type = 'query', $isList = true) {
                if (!in_array($type, ['query', 'mutation'])) throw new InvalidGraphQLTypeException();
    
                $this->graphQl = true;
    
                return $this;
    
                // throw new GraphQLControllerMethodException("This route is for a GraphQL endpoint and can not be accessed.");
            });
    
    $graphQlRoutes = collect(Router::getRoutes())->filter(function($route) {
                return isset($route->graphQl) && $route->graphQl;
            });
    

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 2018-07-19
      • 2020-09-30
      • 1970-01-01
      相关资源
      最近更新 更多