I'm working on cakephp, make an http client where the driver is like this
public function index()
{
$http = new Client();
$response = $http->get('http://localhost/paginaws/articles/index.json');
$json = $response->json;
$valor = $response->body;
$this->set(compact(['valor']));
}
and what I want is to pass it to a view that is going to be a table. I know I have to use a foreach but it does not show me anything. When doing a var_dump shows me that it is an object type.
Related
I want to test my API function by sending array of objects via postman
When I send my request in JSON format to the function and then looping through the array to access each object property it gives me the following error:
https://i.imgur.com/QV9MDsm.jpg
Here is my request:
https://i.imgur.com/4584wf3.jpg
I searched how to send an array of objects using postman and found that I am doing it the right way
I selected row under body section so I can add my request body and selected it's format as JSON and added "Content-Type: application/json" to the request header
My API function:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$newMachine = new Machine;
$newMachine->machine_no = $machine->machineNo;
$newMachine->account_type = $machine->accountType;
$newMachine->machine_type = $machine->machineType;
$newMachine->retialer_id = $retailer->retailerId;
$newMachine->save();
}
}
I expect that i can access each array object properties as a PHP object but I found that it is not an object by testing it using is_object() function:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
return response()->json(is_object($machine));
}
}
I do not know if the problem is within my request or something that I might misunderstand while retrieving data of the request in my controller function
Either it is an array and in that case, you can call
$object = (object) $machine;
Or it is a string aka JSON, you can call
$object = json_decode($machine);
Or if it is an object/array use
$machine['machineType'];
Also please add a dump of the $machine var
EDIT
Try sending the request not using [] because they will be converted into an array with objects in it, instead, if you remove the [] and only have {} it should only be one object in the request
"machineInfo" : {
"machineNo" : "1123213",
"accountType" : "Paid",
//...rest here..
}
Try this:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$object = (object) $machine;
return response()->json(is_object($object));
}
}
Since your request sends data as an array, you can access the elements as so :
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$newMachine = new Machine;
$newMachine->machine_no = $machine['machineNo'];
$newMachine->account_type = $machine['accountType'];
$newMachine->machine_type = $machine->['machineType'];
$newMachine->retialer_id = $retailer->['retailerId'];
$newMachine->save();
}
}
I am passing a POST request with 3 variables
Id (Randomly Generated),
Name (Specified)
Capacity (Specified)
from an Angular Service post. These are in the payload of the POST, and also visible in $request variable in the Laravel resource controller method "store()".
public function store(Request $request)
{
$servers = new Server();
return $request->getContent();
}
Here in Chrome's developer tool>network>POST request>on preview I get this
[{name: "bakar", capacity: 50, id: 8012}]
0: {name: "bakar", capacity: 50, id: 8012}
but when I use
public function store(Request $request)
{
$servers = new Server();
$data = $request->getContent();
$servers->id = $data->id;
$servers->name = $data->name;
$servers->capacity = $data->capacity;
$servers->save();
}
In the above method I got an error exception stating:
" Trying to get property of non-object "
How can I solve this?
Based on your JSON sample, $data should contain an array, which then contains a single object at its first index.
Therefore you cannot do e.g. $data->id because that's assuming that $data has a property called $id...it doesn't, the object at its first index does.
So simply $data[0]->id would allow you to access that index, and then access the $id property of the object at that index. Of course if your request contained multiple items in the array, you might need to use a loop to go through them all and get the values. It depends what you're expecting and what you intended to do with it.
Or, it may be the case that your PHP is correct, and it's your client which is sending the data in the wrong format. It's not clear what the desired outcome actually is.
Edit:
Since it appears that $data is still a JSON string when it arrives in your store() function, you need to decode it. So first write
$data = json_decode($request->getContent());
(instead of $data = $request->getContent();) and then proceed as above.
Complete sample:
public function store(Request $request)
{
$servers = new Server();
$data = json_decode($request->getContent());
$servers->id = $data[0]->id;
$servers->name = $data[0]->name;
$servers->capacity = $data[0]->capacity;
$servers->save();
}
Before I start, I want to let you know I'm really a noob in PHP and this is the first API I'm making.
It works pretty good if I want to echo one array of information (for example food details), but when I try to do the same with multiple items it returns empty.
I've checked the variable values in debug. It's fine in debug and I see an array which contains multiple sub arrays.
My code
$app->get('/allfoods', 'authenticate', function () use ($app) {
global $user_id;
$db = new FoodHandler();
// In here i get foods with their details via mysql
$result = $db->GetAllFoods();
$response = array();
$response["error"] = false;
$response["foods"] = array();
// looping through result and preparing food array
while ($row = $result->fetch_assoc()) {
$tmp = array();
$tmp['food_id'] = $row['food_id'];
$tmp['food_name'] = $row['food_name'];
$tmp['food_desc'] = $row['food_desc'];
$tmp['food_category'] = $row['food_category'];
$tmp['food_creationDate'] = $row['food_creationDate'];
array_push($response["foods"], $tmp);
}
echoRespnse(200, $response);});
My output function (which works great if there is no array in my array)
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
// Http response code
$app->status($status_code);
// setting response content type to json
$app->contentType('application/json');
echo json_encode($response);
}
$app->run();?>
What is my setup?
Localhost wamp with php 7.2.4
Apache 2.4.33
Mysql 5.7.21
I'm also using Postman to send my request (I also tried it in C#, both give back empty content)
I see several issues with your code. First, there is a problem with your route definition. When defining a route, you should pass two arguments to the get method: a pattern (a string,/allfoods in your case) and an instance of Clousure (a callable, your route callback, the anonymous function in your case.) More details in official docs.
So, first thing is to remove the authenticate string from method parameters and change your route definition to this:
$app->get('/allfoods', function ($request, $response, $args) {
// Body of the function goes here
});
Please note I also removed the use ($app) as you have access to application instance uising $this keyword, so no need for that (described in official docs as well).
Second thing is about generating the response. When using Slim framework it is always a good idea to return the $response object instead of echoing response (read more in official docs). Thisgives you some advantages, for example the helper method whitJson helps you whit generating JSON output.
To refine your whole code in a more Slim-ish way:
$app->get('/allfoods', function ($request, $response, $args) {
global $user_id;
$db = new FoodHandler();
// In here i get foods with their details via mysql
$result = $db->GetAllFoods();
$data= array();
$data["error"] = false;
$data["foods"] = array();
// looping through result and preparing food array
while ($row = $result->fetch_assoc()) {
$tmp = array();
$tmp['food_id'] = $row['food_id'];
$tmp['food_name'] = $row['food_name'];
$tmp['food_desc'] = $row['food_desc'];
$tmp['food_category'] = $row['food_category'];
$tmp['food_creationDate'] = $row['food_creationDate'];
array_push($data["foods"], $tmp);
}
// Return JSON data using helper method
return $response->withJson($data);
}
And you won't need the echoResponse function anymore.
l am writing an application that makes a call to an api then returns some data. However l am stuck on populating the database with the data from the API. l tried looking through the decoded json array of object but that for some reason throws an error. my code is as below:
class DefaultController extends Controller
{
public function indexAction()
{
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', API);
$data = json_decode($response->getBody()->getContents(), true);
$request = new Request();
foreach ($data as $data) {
$request->setName($data['name']);
}
$em = $this->getDoctrine()->getManager();
$em->persist($request);
$em->flush();
return new Response('Saved new product with id '.$request->getId());
return $this->render('ApiBundle:Default:index.html.twig');
}
For some reason the loop is not working. Is there a reason why this loop wont work and any work around?
Not certain, but in your for loop you are using '$data' twice. Instead should be (used $d instead):
foreach ($data as $d) {
$request->setName($d['name']);
}
Also, you could try dumping $data to see what it contains.
I'm trying to retrieve a result from a guzzle json post using simple php.
this is my function in file1.php EDITED this file is in a laravel 5.3 project
public function getPhotos($properties)
{
$codes = [];
foreach($properties as $property)
{
$codes[$property['codigo']] = $property['cod_filial'];
}
$client = new Client();
$response = $client->request('POST', 'http://local.app/file2.php', ['json' => \GuzzleHttp\json_encode($codes)]);
var_dump($response); exit;
}
and this is my file in a local url http://local.app/file2.php edited this file is in a project outside laravel and i have endpoint configured pointing.
<?php
$input = file_get_contents('php://input');;
$input = json_decode($input);
return $input;
Guzzle response is empty and i'm not figuring out what i'm doing wrong.
Can someone help me? Thanks a lot.
1) Try in your first file:
var_dump($response->getBody()->getContents());
// or
var_dump((string)$response->getBody());
2) Read the documentation about json option more carefully, this option accepts simple PHP array, you should not call json_encode manually.