Using Guzzle with Laravel Example

laravel 56 guzzle output

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. I am going to show step by step tutorial using Guzzle with Laravel. With guzzle, we will send http request to server and get http response. It is alternate to CURL which provide more features along with easy user interface. Different methods you can send with Guzzle are GET, DELETE, HEAD, PATCH, POST and PUT. Now, let’s get start integrating with laravel.

Install Guzzle

You can install Guzzle using composer

composer require guzzlehttp/guzzle

We can now use Guzzle Client class in our application.

Configure Route

You can use on your own. For now, I am defining a route and execute http request from controller. So, let’s define our route for sending a request to server.

Route::get('test-request-with-guzzle', '[email protected]');

Create Controller

Let’s create a new controller to test our Guzzle integration on our application. Simply run the following command inside of your project folder.

php artian make:controller GuzzleController

Modify Controller

Now, let’s open our newly created controller and make some changes. I have commented each line to help you understand the code. Our controller now looks like below:

Output:
laravel 56 guzzle output

Post Request using Guzzle

You can simply send post request like below:

public function postGuzzleRequest()
    {
        $client = new Client();

        $url = "http://myexample.com/api/posts";

        $myBody['title'] = "This is a title";

        $request = $client->post($url,  ['body'=>$myBody]);

        $response = $request->send();
    }

Put Request using Guzzle

public function putGuzzleRequest()
    {
        $client = new Client();

        $url = "http://myexample.com/api/posts/1";

        $myBody['title'] = "This is a title";

        $request = $client->put($url,  ['body'=>$myBody]);

        $response = $request->send();

        dd($response);

    }

Delete Request using Guzzle

public function deleteGuzzleRequest()
    {
        $client = new \GuzzleHttp\Client();

        $url = "http://myexample.com/api/posts/1";

        $request = $client->delete($url);

        $response = $request->send();

        dd($response);
    }

Async Requests

public function promiseGuzzleRequest()
    {
        $client = new Client(['base_uri' => 'http://httpbin.org/']);

        // Initiate each request but do not block
        $promises = [
            'image' => $client->getAsync('/image'),
            'png'   => $client->getAsync('/image/png'),
            'jpeg'  => $client->getAsync('/image/jpeg'),
            'webp'  => $client->getAsync('/image/webp')
        ];

        // Wait on all of the requests to complete. Throws a ConnectException
        // if any of the requests fail
        $results = Promise\unwrap($promises);

        // Wait for the requests to complete, even if some of them fail
        $results = Promise\settle($promises)->wait();

        // You can access each result using the key provided to the unwrap
        // function.
        echo $results['image']['value']->getHeader('Content-Length')[0];
        echo $results['png']['value']->getHeader('Content-Length')[0];

    }

You can send asynchronous request using Guzzle.

$promise = $client->getAsync('http://examlple.com/get');
$promise = $client->postAsync('http://example.com/post');

Concurrent Request

You can also send Concurrent Request using promises and asynchronous requests.

public function promiseGuzzleRequest()
    {
        $client = new Client(['base_uri' => 'http://httpbin.org/']);

        // Initiate each request but do not block
        $promises = [
            'image' => $client->getAsync('/image'),
            'png'   => $client->getAsync('/image/png'),
            'jpeg'  => $client->getAsync('/image/jpeg'),
            'webp'  => $client->getAsync('/image/webp')
        ];

        // Wait on all of the requests to complete. Throws a ConnectException
        // if any of the requests fail
        $results = Promise\unwrap($promises);

        // Wait for the requests to complete, even if some of them fail
        $results = Promise\settle($promises)->wait();

        // You can access each result using the key provided to the unwrap
        // function.
        echo $results['image']['value']->getHeader('Content-Length')[0];
        echo $results['png']['value']->getHeader('Content-Length')[0];

    }

You can find more examples and documentations in detail at this guzzle official documentation.

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here