Skip to content

Commit

Permalink
[11.x] Ability to generate URL's with query params (#51075)
Browse files Browse the repository at this point in the history
* Add ability to generate a URL with query parameters

* Add tests

* CS fixes

* formatting

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
stevebauman and taylorotwell authored Apr 16, 2024
1 parent 248e117 commit 685627d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Illuminate/Routing/UrlGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
15 changes: 15 additions & 0 deletions tests/Routing/RoutingUrlGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit 685627d

Please sign in to comment.