How to use Rewrite this code with GuzzleHttp

Issue

I wanted to use Http facade in Laravel 5.8 but I noticed that Http facade is not included in this version of Laravel so I installed GuzzleHttp.

But now I don’t know how to rewrite this code with this package:

public function getAddress(Request $request)
    {
        $response=Http::timeout(15)->withHeaders([
            
            'Api-Key' => 'api-key',
        ])->get('https://api.sitename.org/v4/reverse',[
            "lat"=>$request->input('latitude'),
            "lng"=>$request->input('longitude')
        ]);
        $address=$response->json()['formatted_address'];
       return view('address.index',compact('address'));
    }

So how can I properly rewrite this code using GuzzleHttp in order to use the Http ?

Solution

Since guzzle follows psr-7 (I think) there is no builtin method to decode response other things or obvious to you I guess

try {
    $client = new \GuzzleHttp\Client();
    $response = $client->get('https://api.sitename.org/v4/reverse', [
        RequestOptions::HEADERS => [
            'Api-Key' => 'api-key',
        ],
        RequestOptions::QUERY   => [
            "lat" => $request->input('latitude'),
            "lng" => $request->input('longitude')
        ],
    ]);

    $response = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);

    dd($response);
} catch (ClientException $e) {
    // Handle error here
}

Answered By – AH.Pooladvand

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published