0

How can I send data from controller to external api in Laravel?

public function syncData(Request $request)
{
    $datas = Data::all();
    $newDatas = NewData::all();
    $url = 'mydomain.com/api/sync-data';
}

I want to send $datas and $newDatas to $url through Laravel controller and perform some actions on those data. How can I achieve that?

3
  • you need to use curl for that Commented Mar 6, 2021 at 6:35
  • how to use curl a samle code will be helpful to me Commented Mar 6, 2021 at 6:36
  • see the answer section please Commented Mar 6, 2021 at 6:38

2 Answers 2

2

You could use the Laravel HTTP Client (which is a wrapper for Guzzle HTTP Client) to perform a request to that API.

use Illuminate\Support\Facades\Http;

$response = Http::post('mydomain.com/api/sync-data', [
    'data' => Data::all(),
    'newdata' => NewData::all(),
]);
Sign up to request clarification or add additional context in comments.

2 Comments

How will I echo data in external api?
I am not quite sure what you mean by that. You may use the response variable to perform further steps and handle the APIs response. or are you in control of the „external“ API as well? Are you asking how to receive and handle request send from this snippet? That may be a completely other topic and you may want to open a new question...
1
public function syncData(Request $request)
{
    $datas = Data::all();
    $newDatas = NewData::all();
    $url = 'mydomain.com/api/sync-data';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  json_encode($datas));
        $output = curl_exec($ch);
        curl_close($ch);  
}

let me know if it is helpful. important things to notice here. you have to know what your external API type is. is it POST or in GET method. my example above is just a sample code to make you understand how you will use curl it is not tested in regard to your context

14 Comments

Can I dd this data in my domain?
dd what ? can you please explain more ?
I mean how can i verify if data is sent to url?
My method is type POST
well, in this case you have to know what your external API required. having said that I meant. what are the key value pair like name should exactly be same. you can look at it by reading the external API documentation. on the other hand, you can always dd your data before sending to curl.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.