Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Ability to generate URL's with query params #51075

Merged
merged 4 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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