Laravel 9 Guzzle Http Requests with Http Client Example

This comprehensive tutorial helps you understand how to make HTTP POST & GET Requests in Laravel application using PHP Guzzle.

Laravel offers an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications.

Laravel’s wrapper around Guzzle is focused on its most common use cases and a wonderful developer experience.

This Laravel Guzzle HTTP client example tutorial is a step by step guide; it raises the curtains from making HTTP Requests in Laravel enigma.

After completing this tutorial, you will be able to make HTTP requests recklessly in the Laravel project.

So let’s get started.

Create Laravel Project

You can create a new application using given below command:

composer create-project laravel/laravel --prefer-dist laravel-guzzle-http-example

Install Guzzle HTTP Client

Once the package is installed, afterward, you can make the HTTP requests synchronously or asynchronously.

Run the below command to install the Guzzle Http package:

composer require guzzlehttp/guzzle

Guzzle HTTP Requests Requests

Create a new controller where all the Guzzle HTTP Requests will reside:

php artisan make:controller ProductController

Put the given below code in app\Http\Controllers\ProductController.php file:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;


class ProductController extends Controller
{
    // GET
    public function httpGet()
    {
        $httpClient = new \GuzzleHttp\Client();
        $req = $httpClient->get('http://endpoint.com');
        $res = $req->getBody();
       
        dd($res);
    }

    // POST
    public function httpPost()
    {
        $httpClient = new \GuzzleHttp\Client();
        $api = "http://endpoint.com/api/product";
    
        $contentBody['name'] = "Product Demo";
        $req = $httpClient->post($api,  ['body'=>$contentBody]);
        $res = $req->send();
        
        dd($res);
    }

    // PUT
    public function httpPut()
    {
        $httpClient = new \GuzzleHttp\Client();
        $api = "http://endpoint.com/api/product/1";
        $contentBody['name'] = "Product Demo";
        $req = $httpClient->put($api,  ['body'=>$contentBody]);
        $res = $req->send();
       
        dd($res);
    }

    // DELETE
    public function httpDelete()
    {
        $httpClient = new \GuzzleHttp\Client();
        $api = "http://endpoint.com/api/product/1";
        $req = $httpClient->delete($api);
        $res = $req->send();
    
        dd($res);
    }    

}

This was just the tip of the iceberg; nevertheless, it will give you an essential idea of how to get started with making HTTP Requests in Laravel with Guzzle Http Client.