Skip to content

Commit

Permalink
Add withQueryParameters to the HTTP client
Browse files Browse the repository at this point in the history
Some APIs require some query parameters to be always set. For example auth token (even though this isn't a great practice).

With this new helper, we can create a macro with the query parameter always set.
  • Loading branch information
mnapoli committed May 31, 2023
1 parent 693e0c7 commit e878d16
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Illuminate/Http/Client/PendingRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,21 @@ public function withCookies(array $cookies, string $domain)
});
}

/**
* Set the given query parameters in the request URI.
*
* @param array $parameters
* @return $this
*/
public function withQueryParameters(array $parameters)
{
return tap($this, function () use ($parameters) {
$this->options = array_merge_recursive($this->options, [
'query' => $parameters,
]);
});
}

/**
* Specify the maximum number of redirects to allow.
*
Expand Down
13 changes: 13 additions & 0 deletions tests/Http/HttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,19 @@ public function testWithCookies()
$this->assertSame('https://laravel.com', $responseCookie['Domain']);
}

public function testWithQueryParameters()
{
$this->factory->fake();

$this->factory->withQueryParameters(
['foo' => 'bar']
)->get('https://laravel.com');

$this->factory->assertSent(function (Request $request) {
return $request->url() === 'https://laravel.com?foo=bar';
});
}

public function testGetWithArrayQueryParam()
{
$this->factory->fake();
Expand Down

0 comments on commit e878d16

Please sign in to comment.