From 685627d76f1675fddea8560b129ff76364f4eeec Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Tue, 16 Apr 2024 14:00:47 -0400 Subject: [PATCH] [11.x] Ability to generate URL's with query params (#51075) * Add ability to generate a URL with query parameters * Add tests * CS fixes * formatting --------- Co-authored-by: Taylor Otwell --- src/Illuminate/Routing/UrlGenerator.php | 20 ++++++++++++++++++++ tests/Routing/RoutingUrlGeneratorTest.php | 15 +++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/Illuminate/Routing/UrlGenerator.php b/src/Illuminate/Routing/UrlGenerator.php index 74c40d87cbbd..10f18af5ca48 100755 --- a/src/Illuminate/Routing/UrlGenerator.php +++ b/src/Illuminate/Routing/UrlGenerator.php @@ -230,6 +230,26 @@ public function to($path, $extra = [], $secure = null) ).$query; } + /** + * Generate an absolute URL with the given query parameters. + * + * @param string $path + * @param array $query + * @param mixed $extra + * @param bool|null $secure + * @return string + */ + public function query($path, $query = [], $extra = [], $secure = null) + { + [$path, $existingQueryString] = $this->extractQueryString($path); + + parse_str(Str::after($existingQueryString, '?'), $existingQueryArray); + + return $this->to($path.'?'.Arr::query( + array_merge($existingQueryArray, $query) + ), $extra, $secure); + } + /** * Generate a secure, absolute URL to the given path. * diff --git a/tests/Routing/RoutingUrlGeneratorTest.php b/tests/Routing/RoutingUrlGeneratorTest.php index 6fdd50f2ce2a..a19edaeaad19 100755 --- a/tests/Routing/RoutingUrlGeneratorTest.php +++ b/tests/Routing/RoutingUrlGeneratorTest.php @@ -42,6 +42,21 @@ public function testBasicGeneration() $this->assertSame('https://www.foo.com/foo/bar', $url->to('foo/bar')); } + public function testQueryGeneration() + { + $url = new UrlGenerator( + new RouteCollection, + Request::create('http://www.foo.com/') + ); + + $this->assertSame('http://www.foo.com/foo/bar?', $url->query('foo/bar')); + $this->assertSame('http://www.foo.com/foo/bar?0=foo', $url->query('foo/bar', ['foo'])); + $this->assertSame('http://www.foo.com/foo/bar?baz=boom', $url->query('foo/bar', ['baz' => 'boom'])); + $this->assertSame('http://www.foo.com/foo/bar?baz=zee&zal=bee', $url->query('foo/bar?baz=boom&zal=bee', ['baz' => 'zee'])); + $this->assertSame('https://www.foo.com/foo/bar/baz?foo=bar&zal=bee', $url->query('foo/bar?foo=bar', ['zal' => 'bee'], ['baz'], true)); + $this->assertSame('http://www.foo.com/foo/bar?baz[0]=boom&baz[1]=bam&baz[2]=bim', urldecode($url->query('foo/bar', ['baz' => ['boom', 'bam', 'bim']]))); + } + public function testAssetGeneration() { $url = new UrlGenerator(