Guzzle http client GET and POST request example in Laravel 5

July 31, 2017 | Category : Laravel PHP

today we will learn how to send request to server using Guzzle http client in laravel 5 application. As we know sometimes we require to use api of other website like facebook, instagram, wordpress etc, and we have to use their api then we have to two options curl and another is http guzzle. So i think laravel provide Guzzle http client composer package and it's amazing. we simply use that package and get api response in json or html as we need.

So, we have to just use guzzlehttp/guzzle composer package and we can simply use their methods that way we don't require to run curl request or anything. So let's see how it works on get request with Guzzle http client, post request with Guzzle http client, head request with Guzzle http client, put request with Guzzle http client, delete request with Guzzle http client, patch request with Guzzle http client, potions request with Guzzle http client.

Here i will show you how to run those example one my one in your controller method.

Install guzzlehttp/guzzle package:

now we will install guzzlehttp/guzzle package and then we can easily use thir method So let's just run bellow command.

composer require guzzlehttp/guzzle:~6.0

Requests Using Guzzle:

Now here i will show you how to run all above listed request you can use following controller method:

Get Request:

public function getGuzzleRequest()

{

$client = new \GuzzleHttp\Client();

$request = $client->get('http://myexample.com');

$response = $request->getBody();


dd($response);

}

Post Request:

public function postGuzzleRequest()

{

$client = new \GuzzleHttp\Client();

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

$myBody['name'] = "Demo";

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

$response = $request->send();


dd($response);

}

Put Request:

public function putGuzzleRequest()

{

$client = new \GuzzleHttp\Client();

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

$myBody['name'] = "Demo";

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

$response = $request->send();


dd($response);

}

Delete Request:

public function deleteGuzzleRequest()

{

$client = new \GuzzleHttp\Client();

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

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

$response = $request->send();


dd($response);

}

As above example, you can see how it works.

I hope you found your best solution...