Laravel 7|8 PHP Guzzle Http Client GET & POST Examples

Last updated on by Digamber
How can Guzzle HTTP Client help you make the GET and POST requests in PHP Laravel 7? In this tutorial, we will try to answer that. If you are looking for Laravel Guzzle http client example all over the internet, then your quest ends here.

Laravel Guzzle HTTP Client Example

If i talk about the primordial era of web development, then that time we used to rely on cURL for the similar task. But as time went by, there were many improvements. Out of that development, Guzzle is one, i would talk about Guzzle Http client today.

In this tutorial, we will look at how to create the Guzzle Http Client in Laravel 7 and learn to send the HTTP requests.

Install Guzzle Http Package

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. It provides the simple yet powerful interface for sending POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc…

Ideally, to send HTTP requests, we require to install the guzzlehttp/guzzle package using Composer package manager.

composer require guzzlehttp/guzzle

The best thing about Guzzle 6, which attracts my attention towards it, you can simultaneously make synchronous and asynchronous requests from the same interface. Likewise, this offers boundless configurations to play along with http requests.

Guzzle HTTP Client CRUD Requests

Information provided below can give you a rough idea about making GET, POST, PUT, and DELETE requests with Guzzle 6 HTTP Client library in laravel.

Guzzle GET Request

public function guzzleGet()
{
    $client = new \GuzzleHttp\Client();
    $request = $client->get('http://testmyapi.com');
    $response = $request->getBody();
   
    dd($response);
}

Guzzle POST Request

public function guzzlePost()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://testmyapi.com/api/blog";

    $myBody['name'] = "Demo";
    $request = $client->post($url,  ['body'=>$myBody]);
    $response = $request->send();
    
    dd($response);
}

Guzzle PUT Request

public function guzzlePut()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://testmyapi.com/api/blog/1";
    $myBody['name'] = "Demo";
    $request = $client->put($url,  ['body'=>$myBody]);
    $response = $request->send();
   
    dd($response);
}

Guzzle DELETE Request

public function guzzleDelete()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://testmyapi.com/api/blog/1";
    $request = $client->delete($url);
    $response = $request->send();

    dd($response);
}