Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

carestad's avatar

How to utilise Laravel's route parameter parser?

I want to write a redirect controller method that is able to parse a destination string that is shaped the same way as a Route string in Laravel, for instance:

/foo/bar/{id}

So that I can set up a route to redirect with parameters, like:

Route::any('/old/url/{id}', 'RedirectController@redirectWithParameters')
    ->defaults('to', '/new/url/{id}');

The RedirectController's method will look something like this:

public function redirectWithParameters(Request $request) {
    $route = $request->route();
    $to = $route->parameter('to');
    $parsedTo = SomeLaravelOrSymfonyComponent::parseAndBindRouteString($to, $route->parameters());

    return redirect($parsedTo, 302);
}

I haven't been successful in finding the exact part of Laravel or Symfony that does the parsing and matching yet, and if so, I might have to create an instance of some sort of routing component in either framework. As long as the overhead isn't insane I am willing to do this just so I can preserve the same syntax.

Is this doable somehow? Anyone have any insight to which component I should include or use for this?

0 likes
3 replies
tykus's avatar

You can build the new URL from the Request:

Route::redirect('/old/{id}', url('/new', request()->segment(2)));
carestad's avatar

Was not aware of that, but it still isn't quite as "safe" as if I was able to map the ID parameter to wherever I want in the "destination" URL though.

carestad's avatar

This also does not work with php artisan route:cache which is one of the reasons why I am "cleaning up" my routes as well.

Please or to participate in this conversation.