Saumil
Saumil

Reputation: 2517

How to send data to an API in PHP Laravel?

I'm new to Laravel framework so I'm having a hard time to do something very trivial. The main idea is to contact an API and get its response. Below is my function where I'm having error,

public function verification($id=null){
        try{
             $res = $client->createRequest('POST','http://35.161.181.102/api/socialverify/linkedin',['headers' => $headers , 'body' => $urlclean]);  
             $res= $client->send($res);  
         }catch(\GuzzleHttp\Exception\RequestException $e) {
             \Log::info($e->getMessage());
             \Log::info($e->getCode());
             \Log::info($e->getResponse()->getBody()->getContents());
         }
    }

When I run the above function I'm getting the error shown below,

Illegal string offset 'id'

Any pointers on what I'm doing wrong and how can I solve it.

Any help is appreciated. Thank in advance.

Upvotes: 1

Views: 4391

Answers (2)

mohamad
mohamad

Reputation: 1

you can try this way:

use Illuminate\Support\Facades\Http;

   $response = Http::withHeaders($header)
        ->post($url, [
             $data
        ]);

Upvotes: 0

Lionel Chan
Lionel Chan

Reputation: 8059

What do you see in your /storage/logs/laravel.log?

I assume Client is Guzzle Client and by default Guzzle throws RequestException whenever there is a request issue. See Documentation. So why not try to do this and see what's the error responded from Guzzle:

try {
    $response = $client->post('http://link-to-my-api', array(
        'headers' => array('Content-type' => 'application/json'),
        'body' => $data
    ));
    $response->send(); 
}catch(\GuzzleHttp\Exception\RequestException $e) {
    \Log::info($e->getMessage());
    \Log::info($e->getCode());
    \Log::info($e->getResponse()->getBody()->getContents());
}

And check your /storage/logs/laravel.log to see the logs being printed.

Upvotes: 1

Related Questions