Laravel 4 make post request from controller to external url with data

陌路散爱 提交于 2019-12-01 03:07:36

Let me clarify some stuff and try to point you in the right direction.

First, what you're attempting to do sounds like "making an API request from your web app". The difference in that wording in how I stated it vs yours is that it's more general.

  1. You can make an API request anywhere in your application, not necessarily in your controller (Don't be afraid to make extra classes/models for things like API calls!)
  2. I'm curious about why it "has to be" done in your controller? What's your use case?
  3. AJAX doesn't exist on the server-side (in PHP). That's purely a javascript-specific "technology" that describes javascript making a request to a URL on the client-side.

Lastly, what are you trying to do? Do you need a user to be redirected? Or do you need to make an API call and parse the result within your application?

The cURL request you've attempted should work for making an API request. That's one of the main ways of making an API request within PHP code. It won't, however, allow a user on the front-end to see that request being made and processed. With cURL (and any API request), the processing is all happening behind the scenes in your PHP (which your users can't see).

We can use package Guzzle in Laravel, it is a PHP HTTP client to send HTTP requests.

You can install Guzzle through composer

composer require guzzlehttp/guzzle:~6.0

Or you can specify Guzzle as a dependency in your project's existing composer.json

{
   "require": {
      "guzzlehttp/guzzle": "~6.0"
   }
}

Example code of POST Request in laravel, using Guzzle is as shown below,

use GuzzleHttp\Client;
class yourController extends Controller {
public function saveApiData()
{
    $client = new Client();
    $res = $client->request('POST', 'https://url_to_the_api', [
        'form_params' => [
            'client_id' => 'test_id',
            'secret' => 'test_secret',
        ]
    ]);

    $result= $res->getBody();
    dd($result);

}

minorgod

Either use CURL the way you've been trying, or check this thread for a brief answer on doing it with the Guzzle http client. Guzzle seems to be the preferred client for use with Laravel...

Call external API function from controller, LARAVEL 4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!