Alen
Alen

Reputation: 1291

How do I call an API in controller function

I have a function in controller and I want to call an HTTP request passing url like GET request in AJAX but I couldn't figure how do I use it using php I tried this

public function sendAPIRequest()
{
    $url = "https://myapi.com?apikey=".$api."&message=".$message."&receiver=".$receiver;
    //This is what I tried
    file_get_contents($url);
    //But it didn't work
}

Upvotes: 0

Views: 49

Answers (1)

Mortada Jafar
Mortada Jafar

Reputation: 3679

you can use Guzzle Package for Laravel , Guzzle PHP

    $client = new \GuzzleHttp\Client();
$res = $client->request('GET', "https://myapi.com?apikey=".$api."&message=".$message."&receiver=".$receiver);
echo $res->getStatusCode();
// 200
echo $res->getHeaderLine('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// '{"id": 1420053, "name": "guzzle", ...}'

Upvotes: 1

Related Questions