how to get property from api body in laravel? - database

I am sending object with API Body Now I need to get One property from that object and I also need to modify that property in the object how I can do this .
Here is my laravel controller function
public function advanceOrder(Request $request)
{
try{
$result = $request->getContent();
DB::table('advance_orders')->insert(['data'=> $result]);
}catch(Exception $e)
{
DB::table('advance_orders')->insert(['data'=> $e->getMessage()]);
}
}
Here is the object I am getting from api
I want to get delivery_datetime property from object and also want to modify property in that object
{"paymethod_id":1,"business_id":76,"delivery_type":1,"driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":"2020-12-09 00:23:00","location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":2,"value":"Esperar en la entrada","$$hashKey":"object:701"},"delivery_cost_new":20,"products":"[{\"id\":48732,\"code\":\"NLNyEp\",\"quantity\":1,\"options\":[],\"ingredients\":[]}]","customer_id":129731,"customer":"{\"id\":129731,\"name\":\"bil\",\"middle_name\":null,\"lastname\":\"ar\",\"second_lastname\":null,\"photo\":null,\"email\":\"bilal1212#gmail.com\",\"cellphone\":\"0213123132131\",\"address\":\"Coalcomán, Michoacán, Mexico\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":\"sss\",\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}"}

You need to deserialize your object first because the getContent() method returns a string. Just use json_decode() method.
$result = json_decode($request->getContent(), true);
And from now on you can use data from your JSON object as array fields.
dd($result['delivery_datetime']);
You can also modify your data and serialize it again if you need to persist a JSON object.
$result = json_decode($request->getContent(), true);
$result['driver_tip'] = 50;
$modifiedResult = json_encode($result);
dd($modifiedResult);

You can use like this,
public function advanceOrder(Request $request){
try{
$result = json_decode($request->getContent(), true);
$your_final_result = $result['delivery_datetime'];
dd($your_final_result );
}catch(Exception $e)
{
DB::table('advance_orders')->insert(['data'=> $e->getMessage()]);
}
}

Related

save mathod in database cause Array to string conversion error in laravel

when I execute custom command with
php artisan query:all
every thing is good except error shown in console the error is
Array to string conversion
and the data is stored to database I did not understand the cause of this error and it's hidden when hide save to database method
the code of my service which the problem cause inside it is
<?php
namespace App\Services;
use Carbon\Carbon;
use GuzzleHttp\Client;
use App\Models\weatherStatus;
use Illuminate\Support\Collection;
class ApixuService
{
public function query(string $apiKey, Collection $cities): Collection
{
$result = collect();
$guzzleClient = new Client([ //create quzzle Client
'base_uri' => 'http://api.weatherstack.com'
]);
foreach ($cities as $city) {
$response = $guzzleClient->get('current', [
'query' => [
'access_key' => $apiKey,
'query' => $city->name,
]
]);
$response = json_decode($response->getBody()->getContents(), true); //create json from $response
$status = new weatherStatus(); //create weatherStatus object
//adding prameters
$status->city()->associate($city);
$status->temp_celsius = $response['current']['temperature'];
$status->status = $response['current']['weather_descriptions'];
$status->last_update = Carbon::createFromTimestamp($response['location']['localtime_epoch']);
$status->provider = 'weatherstack.com';
//save prameters
$status->save();
$result->push($status);
}
return $result;
}
}
So you can find some clarity in what you are trying to save, do the following:
$response = json_decode($response->getBody()->getContents(), true);
dd($response);
dd() will dump all the data from the $response and exist the script.
One of the values you are trying to save is an array. The field you are trying to save accepts a string and not array.

laravel and json array

I am using laravel 5.3 and angularjs
I submit json from my angularjs like below
{"grc":{"id":1},"floatingGrcs":[{"days":"10","units":"100"},{"days":"20","units":"200"}]}
I accept this array from my laravel controller like below
public function store(Request $request)
{
//how to extract $request object in here
}
I don't know how to extract submitted json array in laravel controller
You can use standard json_decode():
public function store(Request $request)
{
$data = json_decode($request->someJson);
}
You can look at all available data with dd($request->all());
The common-case is that there is no need to post json-encoded data through Angular.
To submit something with Angular, you should use, for example:
$http.post('api/something', {"grc":{"id":1},"floatingGrcs": [..]})
And then there is no need to decode json on the Laravel side:
public function store(Request $request)
{
$request->all(); // to get all fields
$request->grc->id; // to get a specific field
}
I got answer with below code. But i am not sure
$params = json_decode(file_get_contents('php://input'), TRUE);
is this above line of code secure or not.
public function store()
{
$params = json_decode(file_get_contents('php://input'), TRUE);
foreach ($params as $key => $value)
{
if($key == "grc")
{
$grc_id = $value["id"];
}
elseif($key == "floatingGrcs")
{
foreach ($value as $floating)
{
$days = $floating["days"];
}
}
}

symfony2 custom entity to array function

I have to help me convert an entity to array but I have issues resolving associated records, which I need.
However, this gives me an error
The class 'Doctrine\ORM\PersistentCollection' was not found in the
chain configured namespaces ...
The code follows:
public function serialize($entityObject)
{
$data = array();
$className = get_class($entityObject);
$metaData = $this->entityManager->getClassMetadata($className);
foreach ($metaData->fieldMappings as $field => $mapping)
{
$method = "get" . ucfirst($field);
$data[$field] = call_user_func(array($entityObject, $method));
}
foreach ($metaData->associationMappings as $field => $mapping)
{
// Sort of entity object
$object = $metaData->reflFields[$field]->getValue($entityObject);
if ($object instanceof ArrayCollection) {
$object = $object->toArray();
}
else {
$data[$field] = $this->serialize($object);
}
}
return $data;
}
How can I resolve the associated fields into their respective arrays.
I have tried using the built-in, and JMS serialiser, but this gives me issues of nestedness limits, so this is not an option for me.
UPDATE:
I have updated the code to handle instance of ArrayCollection as per #ScayTrase's suggestion. However, the error above is still reported with a one-to-many field map. In debug, the variable $object is of type "Doctrine\ORM\PersistentCollection"
For *toMany association properties implemented with ArrayCollection you should call ArrayCollection::toArray() first. Just check it with instanceof before, like this
if ($object instanceof ArrayCollection) {
$object = $object->toArray();
}

CakePHP 2.5 Datasource, create and return response

I have a specific task to connect CakePHP web application to a remote restful server . I create a datasource, read method works great, but the api after save data return an array of processed data.
Looking for a way to return the data array and use in controller.
My Controller code
public function admin_generate()
{
$data = $this->request->data;
$data['path'] = 'special/generate';
$this->Tool->create();
if($this->Tool->save($data)){
// handle response ????
}
$this->set('data',$data);
$this->set('_serialize','data');
}
In datasource file
public function create(Model $model, $fields = null, $values = null)
{
$data = array_combine($fields, $values);
$api = $this->config['api_path'].$data['path'].'?auth_key='.$this->config['auth_key'];
$json = $this->Http->post($api, $data);
$response = json_decode($json, true);
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
return $response; // ??????
}
Can someone show me the correct way to use the api response data in the controller?
I found a solution, a few minutes after a post question. This can help one of you.
datasource
....
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
// SOLUTION
$model -> code = $response['code'];
$model -> key = $response['key'];
$model -> code_id = $response['code_id'];
return true;
.....
in controller
.....
if($this->Tool->save($data)){
unset($data['path']);
$data['code'] = $this->Tool->code;
$data['key'] = $this->Tool->key;
$data['code_id'] = $this->Tool->code_id;
}
.....

Retrieve data sent by xmlhttprequest in cakephp's controller

I want to send some data (image,text,...) to Posts controller :
$('#home').click(function (){
var xhr = new XMLHttpRequest();
xhr.open("POST","/Portfilo/posts/test",true);
xhr.send("id=10");
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
alert(xhr.responseText);
}
}
});
test action is :
public function test()
{
$this->layout = 'ajax';
//$id = $this->params['named']['id'];
if($this->request->named){
echo "Yesssssss";
}
else {
echo 'Oh No';
}
}
how I cane retrieve these data from this connection (xmlhttprequest).
I read this article but functions or properties like these :
// Passed arguments
$this->request->pass;
$this->request['pass'];
$this->request->params['pass'];
Or
// named parameters
$this->request->named;
return to me "Oh Noooo" message.
How to retrieve these parameter and data s from this request?
If you are sending data through POST method to the test action, you can retrieve it using $this->request->data array, which will contain all variables sent by POST.
In your case, you can try this:
public function test(){
$this->layout = 'ajax';
if($this->request->data['id']){
echo "Yesssssss";
}
else {
echo 'Oh No';
}
}

Resources