简体   繁体   中英

How to extend UrlGenerator to generate links with trailing slashes?

I've modified the htaccess file to force the trailing slash and would now like any url generation within Laravel to automatically add the slash so we don't have so many redirects.

# Force trailing slash.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R=301]

I then created a CustomUrlGenerator class which extends Illuminate\\Routing\\UrlGenerator and I am trying to override the toRoute function...

protected function toRoute($route, $parameters, $absolute)
{
    $route = parent::toRoute($route, $parameters, $absolute);

    return $route . '/';
}

and in AppServiceProvider.php , I've added the following code...

$this->app->bind('url', function($app) {
    return new CustomUrlGenerator($app['routes']->getBindings(), request());
});

Unfortunately, I think this is breaking the app somehow because whenever I try to use anything which uses this function, it can not find the routes, probably because I'm setting this up too early in the life cycle.

As per the code in github, toRoute is protected , meaning that you can't override it as public , change your code as follows:

protected function toRoute($route, $parameters, $absolute)
{
    $route = parent::toRoute($route, $parameters, $absolute);

    return $route . '/';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM