Laravel Key Value Pair in Get Request - php

I'm using Laravel 5.4 and Axios to make async requests to my backend and retrieve data based on the get request parameters of my api endpoint.
I can see in inspector I'm making the following request to the server:
https://website.com/api/users?page=1&sort=%7B%22fieldName%22:%22lname%22,%22order%22:%22asc%22%7D&filter=
Which decodes to:
https://website.com/api/users?page=1&sort={"fieldName":"lname","order":"asc"}&filter=
Looks like I can successfully get pieces of the query via:
return $request->query('sort');
which returns:
data:
fieldName: "lname"
order: "asc"
But when I use:
return $request->query('sort.fieldName');
I don't get anything. Should I not be using the dot notation? How do I get each key / value pair of the sort input? Thanks for any help!

I thought you could use dot notation, but at any rate you could try just converting it from json to an associative array.
$sort = json_decode($request->query('sort'), true);
This should then allow you to do something like, $sort[‘fieldName’]. The true parameter tells the decode to turn it into an associative array versus being returned an object.

Related

How to query parameters in URL - json api

I have to call api url to access the json object from it. in its tutorial, they provide some variables we can access through url, these variables have names different of the attributes name of the json object.
ex: url&parm1=val1
json object
{
"parm1_name": "val1"
}
My question:
How to return specific values depend on the attributes of the json object?
Do we have to use the parameter names which are provided on their website?
what the difference between "?pram1=val" and "pram1=:val"
How to query as we do in databases using greater or less than?
I use PHP and crul to retrieve the json object.
The value that each parameter/s return should be documented by the api and is up to the provider.
Yes, you have to use the parameters the api/website requires to return the value. If the api/website expects a value to return something then you have to provide the expected value. That also means the website will only recognize values that they look for.
The paramaters are key and value so
?param=val1 => key "param" equals "val1"
?param=:val1 => key "param" equals ":val1"
Unless the api provides a way to do then you can't. The limitations of what you can do is set by the api.
Api is essentially this:
<?php
// it gets ?id=val
// so if the GET parameters were ?id=1&name=blue&do=add
// it would only recognize id parameters the other parameters wouldnt change a thing
$val = $_GET["id"];
if $val == 1 {
return $data;
}
?>
API must provide a way for you to e.g. search for "greater & less than" otherwise you cannot do it.

Mongo result as JSON

Using following code to convert as document to JSON is:
print( json_encode((new MongoClient())->db->col->findOne()));
//Output:{"_id":{"$id":"52838520f7c255c009000000"},"test":"test"}
Is there any way to set Mongo to return _id field as string instead of object? Is it safe to return _id value to client side script (as the response of a GET request)
I do not want manually convert _id to string and vice versa when implementing a REST api.
No, there is nothing you can do (mongod in comparison to SQL can not do modification of the fields it is outputting). Therefore you only resort is to do what you didn't want to do (manually convert). But it is not hard, all you need to do is one of these:
(string)$doc['_id'];
(string)$doc->_id;
$doc['_id']->{'$id'};

PHP for catching POST value

How can I catch POST value using PHP for the parameter with multiple third bracket?
Ex.
content[fields][attendees]
content[fields][completed]
Okay, let me post url encoded raw data here:
type=activities.update&objectid=75585970&content%5Bid%5D=75585970&content%5Bname%5D=Order+Received%2F+Processing+request+%28may+need+more+info%29&content%5Bcreated%5D=2013-03-15T16%3A09%3A50%2B00%3A00&content%5Bupdated%5D=2013-03-16T06%3A37%3A01%2B00%3A00&content%5Bviewed%5D=2013-03-16T06%3A35%3A21%2B00%3A00&content%5Blevel%5D=1&content%5Bflagged%5D=0&content%5Btypeid%5D=22&content%5Bparenttypeid%5D=2&content%5Bparent%5D=75585967&content%5Bparentname%5D=Tanmoy+Sadhu+%7C+weew+%7C+RSA&content%5Bitem%5D=75585967&content%5Bitemname%5D=Tanmoy+Sadhu+%7C+weew+%7C+RSA&content%5Bitemtypeid%5D=2&content%5Bposition%5D=2&content%5Bfields%5D%5Battendees%5D=&content%5Bfields%5D%5Bcompleted%5D=1&content%5Bfields%5D%5Btitle%5D=Order+Received%2F+Processing+request+%28may+need+more+info%29+
I've tried with $_POST['content[fields][attendees]'] and $_POST['content\[fields\]\[attendees\]'] but no luck.
Any way to catch that?
Try
echo $_POST['content']['id'];
echo $_POST['content']['name'];
echo $_POST['content']['fields']['attendees'];
etc.
Output from your url parameters:
75585970
Order Received/ Processing request (may need more info)
<-empty string here for attendees
I believe the correct syntax would be
$_POST['content']['field'] etc
so for the example of &content%5Bid%5D=75585970 you can get the value 75585970 by calling
$_POST['content']['id'];
This is because the $_POST value for any particular key is a string (or array in the case the key has brackets).
In this case, $_POST['content'] returns an array of many different key value pairs, and you can access the values using those array keys just like in any multidimensional array.

PHP: How to receive JSON array from iPad app

Disclaimer: I am fairly new to using json.
I am trying to use php to receive json data from an iPAd application. I know how to convert json to an array in php, but how do I actually receive it and store it into a variable so it can be decoded?
Here are a couple examples that I have tried based on google and stackoverflow searches.
$json_request = #file_get_contents('php://input');
$array = json_decode($json_request);
AND ALSO
$array = json_decode($_POST['data'], true);
Any suggestions?
You have the basic idea already.
you should test that the value is set and also strip extra slashes from the incoming string before trying to parse it as JSON.
if(isset($_POST['data'])){
$array = json_decode(stripslashes($_POST['data']),true);
//$array now holds an associative array
}//Data Exists
It also would not be a bad idea before you start working with the array to test that the call to json_decode() was successful by ensuring that $array isn't null before use.
If you do not fully trust the integrity of the information being sent you should do extended checking along the way instead of trusting that a given key exists.
if($array){ // Or (!is_null($array)) Or (is_array($array)) could be used
//Process individual information here
//Without trust
if(isset($array['Firstname'])){
$CustomerId = $array['Firstname'];
}//Firstname exists
}//$array is valid
I in-particular like to verify information when I am building queries dynamically for information that may not be required for a successful db insert.
In the above example $_POST['data'] indicates that what ever called the PHP script did so passing the JSON string using the post method in a variable identified as data.
You could check more generically to allow flexibility in the sending method by using the $_REQUEST variable, or if you know it is coming as via the get method you can check $_GET. $_REQUEST holds all incoming parameters from both get and post.
If you don't know what the name of the variable coming in is and want to play really fast and loose you could loop over the keys in $_REQUEST trying to decode each one and use the one that successfully decoded (if any). [Note: I'm not encouraging this]

null on json data

I am trying to parse this json data from the url but i get NULL how do i fix this issue.
$source = file_get_contents('http://partners.socialvi.be/e414f702cf3db89a2fe58066bbab369d65b6a058/activities/available.json');
$json = json_decode($source);
var_dump($json);
That's because the API returns the data in JSONP format, not pure JSON. Notice the surrounding onSVJson([]). You'll either have to strip this out, or read the API documentation and try another request format. My guess would be that leaving out the final &callback=onSVJson should do the trick.
That's because if you call the url (go to http://partners.socialvi.be/e414f702cf3db89a2fe58066bbab369d65b6a058/activities/available.json?network_user_id=3459874&max_activities=9&callback=onSVJson with your browser) the json that is returned has no values
Remove the last part of the URL (&callback=onSVJson) and it'll work.
Many APIs offer a feature called JSONP, that allows the JSON to be passed to a callback function, in order to simplify access via cross domain JavaScript. But for PHP you don't need that.
The name of the callback function is typically specified using the callback GET parameter. If you leave that out, no callback function is used - just plain JSON.

Categories