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

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;
});

Related

How to send data from controller to rest api in 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

Getting error while passing decoded json data from controller to view

when I use dd($arr) in controller the decoded json data gets printed correctly. How can I pass this decoded json data into my view?
Controller Code
public function test()
{
// $sld = $request['sld'];
// $tld = $request['tld'];
$response = Curl::to('https://reseller.enom.com/interface.asp?command=check&sld=decksys&tld=info&responsetype=xml&uid=resellid&pw=resellpw')
->get();
//check if we are getting a response
$xml = simplexml_load_string($response);
$json = json_encode($xml);
$arr = json_decode($json, true);
dd($arr);
return view('clientlayout.main.test', compact('arr'));
}
Blade File:
`{{ $arr }}`
My Route file is given below:
Route::get('/test','EnomController#test');
How to solve this error?
htmlspecialchars() expects parameter 1 to be string, array given
return view('clientlayout.main.test', compact('arr'))->with('arr', $arr);
and your view: {{ $data['obj'] }} will work.
The answer for this error is already available on stack, you are accessing those objects which are empty or blank here is a link of solution:
htmlspecialchars expects parameter 1 to be string
ok in controller use curl like:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
"https://reseller.enom.com/interface.asp?command=check&sld=decksys&tld=info&responsetype=json&uid=resellid&pw=resellpw");
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
$arr = json_decode(curl_exec($ch), true);
curl_close($ch);
then return data to view, use foreach loop in view like:
#foreach($arr as $item)
{{$item['Command']}}
{{$item['APIType']}}
#endforeach
and want to check before print use isset:
#if(isset($item['Command']))
{{$item['Command']}}
#endif
Hope this help

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!

Mailchimp API status 200 for members who are already subscribed

The following code is working and subscribing new members successfully. However, the status returns 200 even if the email address is already subscribed. I have checked that $member_id is hashing correctly, and despite identical values it still returns 200.
$result = array(
'status' => sync_mailchimp($data)
);
var_dump($result) // 200
function sync_mailchimp($data) {
// Setup our Mailchimp info
$api_key = 'xxxxx';
$list_id = 'ab8abde5bb';
$member_id = md5(strtolower($data['email'])); // lowercase hash of the email
$datacenter = 'us16';
$url = 'https://' . $datacenter . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . $member_id;
$json = json_encode([
'email_address' => $data['email'],
'status' => $data['status']
]);
// Send via curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpcode;
}
I was also having the same issue while using a similar snippet.
Reading the MailChimp API 3.0 docs relating to managing subscribers (specifically the section Subscribe an Address), it was clear that this method was not the correct way to add a new subscriber.
The request type needs to be a POST
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
and must be sent to the endpoint
https://<data_center>.api.mailchimp.com/3.0/lists/<list_id>/members/
The request body containing the JSON is identical.
The response code will be 200 when an email address is added to the list successfully, and 400 when the email address already exists on the list.
Note that this method will not work for updating an existing subscriber – to do that, the request type must be PATCH, and you must use the original endpoint ending with the hashed email address.

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);
}

Resources