Home  >  Q&A  >  body text

php - Laravel的路由怎么匹配?parameter=something

Laravel匹配路由的模式是domain.com/parameter/something/another_parameter/something,这样可以指定匹配Controller的一个方法。那么domain.com/index?parameter=somgthing匹配一个方法,domain.com/index?another_parameter=something匹配另一个方法,有办法可以办到吗?

PHPzPHPz2653 days ago325

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-11 10:11:27

    不能,而且没有理由这么做。
    如果你的参数是有规律的,用斜杠分割。
    如果参数没规律只能用 ? 这种查询参数的话,那就给上级定义路由,再在那个方法里 if ($request['foo'] == 'bar') { return $this->barAction($request); } 。没有规律的参数也没发做路由缓存。
    或者定义一个middleware,专门处理参数然后执行方法调用。但这样的话又基本是放弃使用了 Laravel 的路由功能。
    所以没有理由这么做。

    再比如,5.2之前可以在controller里根据方法名自动匹配路由,因为诸多缺点,5.2之后就废弃了这种路由定义方式。

    reply
    0
  • 迷茫

    迷茫2017-04-11 10:11:27

    laravel本身是没有这种功能的。但是laravel最大的好处是一切都可以扩展定制。

    你可以自己定义个controller或直接定义个RoutesServiceProvider来处理这种情况。关键代码就是取请求中的参数,然后找到对应的函数进行执行,也没啥难的:

            $request = app()->request;
            $httpMethod = $request->method();
            $controllerClass = 'App\\Http\\Controllers\\'. $request->get('controller') . 'Controller';
            $action = $request->get('action');
    
            $classMethod = "do{$httpMethod}{$action}";
    
            try {
                $reflectionMethod = new \ReflectionMethod($controllerClass, $classMethod);
    
                // only public method are allowed to access
                if (!$reflectionMethod->isPublic()) {
                    abort(403, 'Action not allowed');
                }
            } catch (\ReflectionException $e) {
                abort(404, 'Action not found');
            }
    
            return app()->call($controllerClass.'@'.$classMethod);

    reply
    0
  • Cancelreply