Search code examples
phplaravelguzzle

Adding Query string params to a Guzzle GET request without removing existing query params?


I am using guzzle Http client request for GET method, what i am doing i am sending request to some dynamic url which i am fetching from DB and than appending some field into it and sending request Example below :

$this->client->GET("https://webhook.site/bb1ea111-517e-46f5-867e-e956a75753f0?test=id&name=testname", 'query' => [
      'option_1' => string,
      'option_2' => string
   ]);

Now when i send request it goes like below

https://webhook.site/bb1ea111-517e-46f5-867e-e956a75753f0?option_1=string&option_2=string

So it removed default query params from url

Anyone here please let me know what i can update so that it should go like below

https://webhook.site/bb1ea111-517e-46f5-867e-e956a75753f0?test=id&name=testname&option_1=string&option_2=string

Solution

  • You can use http_build_query function and add it to your query string because Guzzle will replace array in query with the existing ones:

    $this->client->GET("https://webhook.site/bb1ea111-517e-46f5-867e-e956a75753f0?test=id&name=testname&" . http_build_query([
        'option_1' => string,
        'option_2' => string
    ]));
    

    Alternatively, you may extract parameters from existing url and send the complete params in Guzzle:

    $url = "https://webhook.site/bb1ea111-517e-46f5-867e-e956a75753f0?test=id&name=testname";
    $query = parse_url($url);
    parse_str($query, $queryParams);
    $params = array_merge($queryParams, [
        'option_1' => string,
        'option_2' => string
    ]);
    $this->client->GET($url, $params);
    

    I personally prefer second option because it is more clear.