How to send HTTP requests from Laravel to another server
Hello friends, In this article, I am gonna show you how to Send HTTP requests such as Get, Post, Put, Patch, Delete requests from Laravel to another server. This is most important for developers because most Laravel developers need to get resources from another server itself. There are many ways to send HTTP requests using Laravel. I am showing the easiest way to send these requests.
Before doing this, you have to verify that your Laravel project has installed the Guzzle package as a dependency of your project. Basically, Laravel automatically includes this dependency by default. But, if you removed the package or somehow its not installed, you have to install it via Composer. You can use below composer code to install Guzzle.
composer require guzzlehttp/guzzle
After installing Guzzle, or if Guzzle is already there, now you can use the Http from your controller and you can request for Get, Post, Put, Patch, and Delete methods from the Http requests. By using these methods you can even call an external API in order to fetch resources. Below are some examples,
Note – at the beginning of your controller, you have to use the Http. else it will not identify the Http code. You can use Http as below example.
use Illuminate\Support\Facades\Http;
Get Method
use Illuminate\Support\Facades\Http;
$response = Http::get('https://nsrtechx.com/getData');
Post Method – (application/json)
use Illuminate\Support\Facades\Http;
$response = Http::post('https://nsrtechx.com/users', [
'name' => 'myname',
'email' => 'myemail@site.com',
]);
Post Method – (application/x-www-form-urlencoded)
use Illuminate\Support\Facades\Http;
$response = Http::asForm()->post('https://nsrtechx.com/users', [
'name' => 'myname',
'email' => 'myemail@site.com',
]);
Request with headers
use Illuminate\Support\Facades\Http;
$response = Http::withHeaders([
'X-First' => 'foo',
'X-Second' => 'bar'
])->post('https://nsrtechx.com/users', [
'name' => 'myname',
'email' => 'myemail@site.com',
]);
Above are some examples of the Http requests with Guzzle dependency. And if you are using Lumen which is a micro framework of Laravel, Also you can use Http request as above. As I mentioned earlier, In Lumen also you have to verify that Guzzle has been installed.
That’s it!! If you have any questions please feel free to comment below.
Or you can check my latest posts from below link.