Laravel route url with query string

后端 未结 4 486
感动是毒
感动是毒 2021-02-02 07:59

On laravel 4 I could generate a url with query strings using the route() helper. But on 4.1 instead of:

$url = url(\'admin.events\', array(\'lang\' => \'en\')         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-02 08:47

    The following was what I needed to do:

    I handle all of my routing in a service provider, where I had defined the following function:

    private function registerRestfulController($prefix, $controllerClass)
    {
        Route::controller($prefix, $controllerClass, $controllerClass::getRouteNames());
    }
    

    getRouteNames is a static method on my BaseController that conventionally returns routes so that RESTful controllers can have automatic named routes.

    The problem I was running into was that this defined the set of wildcard matchers on the route itself - in order to avoid that, I add the following to the private function above:

    foreach ($controllerClass::getRoutesNames() as $name) { 
        $route = Route::getRoutes()->getByName($name);
        $cleanUri = preg_replace('/\/\{\w*\?\}/', '', $route->getUri());
        $route->setUri($cleanUri);
    }
    

    This loads all the routes you are registering at the time and immediately removes wildcards from the URI. You could easily pass a boolean or "white-list" of route names that you want to preserve wildcards for, so that it doesn't stomp all over the Laravel default without the intention. Once you run this, it automatically starts working with query string variables, which I find far preferable to path variables in this instance.

提交回复
热议问题