Reputation: 395
How to make http request to another server through Laravel?
I'll be pleased to provide whatever information you need
any help is much appreciated
Upvotes: 2
Views: 7644
Reputation: 665
If for some reason you are running an old Laravel version or don't want to bother with guzzle, you can always use php-curl:
sudo apt-get install php-curl
Then create a function for your needs eg POST:
function httpPost($url, $data){
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
or GET
public function httpGet($url){
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
Simply call your function in controller:
$response = $this->httpPost($url, $data);
$response = $this->httpget($url);
Where $url is your endpoint where you need to send request and $data - parameters required.
Upvotes: 1
Reputation: 561
First of all run this command
composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
$client = new Client();
$response = $client->get("http://www.somewebsite.com/getSmth");
$response = (string) $response->getBody();
return $response;
getBody() function will return object.
You can use via converting to string and after that if you want you can change it to integer also
$response = (int) (string) $response->getBody();
Upvotes: 0
Reputation: 3216
You can use Guzzle add the dependency package in the composer.json file
{
"require": {
"guzzlehttp/guzzle": "~4.0" //you can change the version
}
}
make composer install or update
To create your very first request with guzzle, a code snippet as simple as below will work:
use GuzzleHttp\Client;
use GuzzleHttp\Message\Request;
use GuzzleHttp\Message\Response;
$client = new Client();
$response = $client->get("https://api.github.com/");
retrun $response;
Upvotes: 1
Reputation: 12276
With 'normal' PHP, you can use Curl to work with the http protocol (POST/GET). If you are using Laravel, you can either build your own curl methods or you can use a 3rd party curl library compatible with composer/Laravel:
https://packagist.org/packages/unikent/curl
Upvotes: 1
Reputation: 146
Depends how complex the request needs to be. You can use curl or even, file_get_contents for simple get requests, or install a package like Guzzle for more complex things.
https://github.com/guzzle/guzzle
Upvotes: 3