Skip to content

Commit

Permalink
[11.x] Replace all backed enums with values when building URLs (#51524)
Browse files Browse the repository at this point in the history
* Replace all enums with values when generating URLs

* Update UrlGenerator.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
stefanvdlugt and taylorotwell authored May 21, 2024
1 parent 41409f4 commit cb567d3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/Illuminate/Routing/UrlGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -525,13 +525,17 @@ public function route($name, $parameters = [], $absolute = true)
public function toRoute($route, $parameters, $absolute)
{
$parameters = collect(Arr::wrap($parameters))->map(function ($value, $key) use ($route) {
$value = $value instanceof UrlRoutable && $route->bindingFieldFor($key)
return $value instanceof UrlRoutable && $route->bindingFieldFor($key)
? $value->{$route->bindingFieldFor($key)}
: $value;

return $value instanceof BackedEnum ? $value->value : $value;
})->all();

array_walk_recursive($parameters, function (&$item) {
if ($item instanceof BackedEnum) {
$item = $item->value;
}
});

return $this->routeUrl()->to(
$route, $this->formatParameters($parameters), $absolute
);
Expand Down
16 changes: 16 additions & 0 deletions tests/Routing/RoutingUrlGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,22 @@ public function testRouteGenerationWithBackedEnums()
$this->assertSame('http://www.foo.com/foo/fruits', $url->route('foo.bar', CategoryBackedEnum::Fruits));
}

public function testRouteGenerationWithNestedBackedEnums()
{
$url = new UrlGenerator(
$routes = new RouteCollection,
Request::create('http://www.foo.com/')
);

$namedRoute = new Route(['GET'], '/foo', ['as' => 'foo']);
$routes->add($namedRoute);

$this->assertSame(
'http://www.foo.com/foo?filter%5B0%5D=people&filter%5B1%5D=fruits',
$url->route('foo', ['filter' => [CategoryBackedEnum::People, CategoryBackedEnum::Fruits]]),
);
}

public function testSignedUrlWithKeyResolver()
{
$url = new UrlGenerator(
Expand Down

0 comments on commit cb567d3

Please sign in to comment.