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(