Skip to content

Commit 685627d

Browse files
[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 <[email protected]>
1 parent 248e117 commit 685627d

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/Illuminate/Routing/UrlGenerator.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,26 @@ public function to($path, $extra = [], $secure = null)
230230
).$query;
231231
}
232232

233+
/**
234+
* Generate an absolute URL with the given query parameters.
235+
*
236+
* @param string $path
237+
* @param array $query
238+
* @param mixed $extra
239+
* @param bool|null $secure
240+
* @return string
241+
*/
242+
public function query($path, $query = [], $extra = [], $secure = null)
243+
{
244+
[$path, $existingQueryString] = $this->extractQueryString($path);
245+
246+
parse_str(Str::after($existingQueryString, '?'), $existingQueryArray);
247+
248+
return $this->to($path.'?'.Arr::query(
249+
array_merge($existingQueryArray, $query)
250+
), $extra, $secure);
251+
}
252+
233253
/**
234254
* Generate a secure, absolute URL to the given path.
235255
*

tests/Routing/RoutingUrlGeneratorTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,21 @@ public function testBasicGeneration()
4242
$this->assertSame('https://www.foo.com/foo/bar', $url->to('foo/bar'));
4343
}
4444

45+
public function testQueryGeneration()
46+
{
47+
$url = new UrlGenerator(
48+
new RouteCollection,
49+
Request::create('http://www.foo.com/')
50+
);
51+
52+
$this->assertSame('http://www.foo.com/foo/bar?', $url->query('foo/bar'));
53+
$this->assertSame('http://www.foo.com/foo/bar?0=foo', $url->query('foo/bar', ['foo']));
54+
$this->assertSame('http://www.foo.com/foo/bar?baz=boom', $url->query('foo/bar', ['baz' => 'boom']));
55+
$this->assertSame('http://www.foo.com/foo/bar?baz=zee&zal=bee', $url->query('foo/bar?baz=boom&zal=bee', ['baz' => 'zee']));
56+
$this->assertSame('https://www.foo.com/foo/bar/baz?foo=bar&zal=bee', $url->query('foo/bar?foo=bar', ['zal' => 'bee'], ['baz'], true));
57+
$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']])));
58+
}
59+
4560
public function testAssetGeneration()
4661
{
4762
$url = new UrlGenerator(

0 commit comments

Comments
 (0)