How to send data from controller to rest api in laravel? - laravel

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?

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(),
]);

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

Related

How to call local api using curl in laravel?

Using laravel api in local API fetch and display data in the view file:
$url = 'http://demo.local:8000/api/category12';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec ($ch);
$err = curl_error($ch); //if you need
curl_close ($ch);
return $response;
If it's a local API, you can treat your controller as a Real Time Facade
Using real-time facades, you may treat any class in your application
as if it were a facade.
For example, let's assume our CategoryController controller has a detail method:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Category;
class CategoryController extends Controller
{
/**
* return the category object for the given id.
*
* #param int $id
* #return response
*/
public function detail($id)
{
return response()->json(['data' => Category::findOrFail($id)]);
}
}
Then you can use it like :
use Facades\App\Http\Controllers\CategoryController;
$category = CategoryController::detail(5);
When the real-time facade is used, the CategoryController
implementation will be resolved out of the service container using the
class name that appears after the Facades prefix
Try this:
$hit = "http://demo.local:8000/api/category12";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $hit,
CURLOPT_USERAGENT => 'http://YOUR-DOMAIN'
));
$resp = curl_exec($curl);
curl_close($curl);
return $resp;

Quick q. Mailchimp API 3.0

Can i use the first script or i need to use the curl option for mailchimp 3.0? I read some posts that the first one may be depreciated.. is that correct? Note that i'm not running on WordPress. Thank you for your fast answers.
<?php
require("vendor/autoload.php");
use \DrewM\MailChimp\MailChimp;
$mc = new MailChimp('apikey');
$email = $_POST['email'];
$subscriber_hash = $mc->subscriberHash($email);
$response = [];
$list_id = 'listid';
$resp = $mc->get("/lists/$list_id/members/$subscriber_hash";
if ($mc->success()) {
$response['message'] = 'Thank you for subscribing to the mailing list';
// User successfully subscribed - set HTTP status code to 200
http_response_code(200);
} else {
$response['message'] = $mc->getLastError();
// User not subscribed - set HTTP status code to 400
http_response_code(400);
}
// Return json-formatted response
echo json_encode($response);
?>
Or should i use this one?
function mc_checklist($email, $debug, $apikey, $listid, $server) {
$userid = md5($email);
$auth = base64_encode( 'user:'. $apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'.api.mailchimp.com/3.0/lists/'.$listid.'/members/' . $userid);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '. $auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
if ($debug) {
var_dump($result);
}
$json = json_decode($result);
echo $json->{'status'};
}
This row is only for stackoverflow not alowing me to post that much code without including more details.
The first is not deprecated. It uses this wrapper to make API calls using the same API version that the second block of code uses. It's just simpler to work with so you don't have to write separate CURL requests for every call. You can also take a look at some of its source code and notice that it uses CURL anyway to make its calls.
So either way will use CURL, and whichever option you choose is simply a matter of preference.
Hopefully that clears it up for you!

in Laravel How to post data to another route in a route ?

I have a Post Route in Laravel, so if a user post data to the route I want to add data to request then posting it to another post route that I have then show the user the result that I get from the second route.
Is there way to do it? or I should use GuzzleHttp?
You can use curl to perform the sub request.
Route::any('/proxy', function (Request $request) {
//Get all of the input from the request and store them in $data.
$data = $request->all();
//initialise your other data.
$data2 = ['xyz' => "xyz"];
$newPayload = array_merge($data, $data2);
$endPoint = "https://example.org";
$ch = curl_init($endPoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $newPayload);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
return (string)$response;
});

how to make Pagination in laravel to return values in json format

I have client controller that sends request and server controller that processes the request and sends response.
How to paginate the response json data in laravel.
Server Controller
public function index() {
$data = languages::where('is_active','1')->orderBy('id','desc')->get();
$response = Response::json($data,200);
return $response;
}
Client Controller
public function index()
{
$url = url('languagesService');
$data = json_encode(array("username" => $this -> username,"password" => $this -> password));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER,false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = CURL_EXEC($ch);
$data = json_decode($response);
return View::make("languages.index")->with("data",$data);
}
I guess, this is quite simple. Have you tried something like :
public function index() {
$data = languages::where('is_active','1')->orderBy('id','desc')->paginate($perPage);
$response = Response::json($data,200);
return $response;
}
UPD:
In case you want to paginate elsewhere of index() action, then you should create manually the paginator object via native Paginator class. You can find additional info here. As quick example, you should do on your client controller:
$paginator = Paginator::make($data, count($data), $perPage);
And then use the $paginator object to achieve what you want.
You can simply return the collection, it will convert to JSON itself.
public function index() {
return languages::where('is_active','1')->orderBy('id','desc')->paginate();
}
// If you add `page` param into URL, Eloquent gets you content for specified page.
$url = url('languagesService', ['page'=>0]);
// $url = url('languagesService', ['page'=>20]);
I advice you send links for previous/next page together with total count of items so that API consumer can retrieve more elements if needed.
public function index() {
$data [
'data' => languages::where('is_active','1')->orderBy('id','desc')->paginate()->toArray(),
'total' => getNumberOfAllEntitiesThatFitFilter(),
'nextPage' => getUrlForNextPage(),
'previousPage' => getUrlForPreviousPage(),
];
return Response::json($data);
}

CodeIgniter redirect to another function when request is made by cURL

I've got a function, "Function A", in a CodeIgniter controller that includes a redirect to another function, "Function B" to send an email when it's done gathering data. My problem is that when I enter Function A's url into the browser, the function works as expected and the redirect to Function B also works... but Function A is called by a cURL script, and when this happens Function A is performed but the redirected Function B does not work. Is it possible to have a redirected function in this scenario (when the request is made via cURL)?
Can you show your CURL code? I think you use something like:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close( $ch );
Check this string (it should set to true):
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
And you can use next thing (in stormdrain's example):
function first_function(){
ob_start();
//do stuff
$this->second_function();
ob_end_flush();
}
function second_function(){
//send email
}
It's hard to say without seeing any code. But, if these functions are in the same controller, you can call the other function when the first completes
function first_function(){
//do stuff
$this->second_function();
}
function second_function(){
//send email
}

Resources