From e878d1619d43095e57db5cc9d85a509b82294ce9 Mon Sep 17 00:00:00 2001 From: Matthieu Napoli Date: Wed, 31 May 2023 18:37:39 +0200 Subject: [PATCH] Add `withQueryParameters` to the HTTP client 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. --- src/Illuminate/Http/Client/PendingRequest.php | 15 +++++++++++++++ tests/Http/HttpClientTest.php | 13 +++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/Illuminate/Http/Client/PendingRequest.php b/src/Illuminate/Http/Client/PendingRequest.php index ceb657736b5d..4f9192941f9a 100644 --- a/src/Illuminate/Http/Client/PendingRequest.php +++ b/src/Illuminate/Http/Client/PendingRequest.php @@ -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. * diff --git a/tests/Http/HttpClientTest.php b/tests/Http/HttpClientTest.php index f15b0ae71d93..20cb5141911a 100644 --- a/tests/Http/HttpClientTest.php +++ b/tests/Http/HttpClientTest.php @@ -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();