i want to generate reports from api external, using guzzle, here is my result
{#430 ▼
+"data": {#427 ▼
+"report_id": "20190801-5f6e21a5"
+"status": 5
+"creation_date": "2019-08-01 13:19:49"
+"due_date": "2019-08-02 13:19:49"
+"data": {#432 ▼
+"chassis_number": "ACR50-0183692"
+"engine": "2AZFE"
+"manufacture_date": "2014-07"
+"registration_date": "2019-04-17"
+"make": "TOYOTA"
+"model": "ESTIMA"
+"displacement": "2360"
+"fuel": "GASOLINE"
}
}
+"error": ""
}
but i dont know how to get the value from this json and save to database. i want to save value from report_id, status, creation date etc
$client = new Client();
$body = $client->request('GET', 'https://xxxxx/api/v1/get-report', [
'headers' => [
'Accept' => 'application/json',
'Carvx-User-Uid' => 'xxxxxx',
'Carvx-Api-Key' => 'xxxxxx',
'needSignature' => '0',
'raiseExceptions' => '1',
'isTest' => '0'
],
'query' => [
'report_id' => $reportId,
'true'=>'1'
]
])->getBody();
$contents = (string) $body;
$data = json_decode($contents);
// dd($data);
//to get value from status
$var_status = var_export($data['status'],true);
$status = substr($var_status, 1, -1);
echo $status;
and i get this error
Cannot use object of type stdClass as array
json_decode by default returns a Stdclass object, with properties representing the keys in the json object.
You can tell json_decode to return an associative array instead by passing true as the second param:
json_decode($contents, true); // returns array
Docs: https://www.php.net/manual/en/function.json-decode.php
Related
i have a array data like this below. i want to save some of it's data not all into mysql table.
when i dd($request->all) data in my controller function it looks like this.
array:1 [
"{"cart":" => array:1 [
"{"product":{"id":1,"category":1,"product_name":"Brinjal 500g","product_image":"1585409454.jpeg","product_price":232,"unit":"500g","product_description":null,"stock":"In Stock","product_status":1,"show":1,"delievery_date":null,"vendor":null,"quantity":18,"item_type":"feature_product","created_at":"2020-03-28T15:30:54.000000Z","updated_at":"2020-03-28T15:30:54.000000Z","deleted_at":null,"categories":{"id":1,"category_name":"Fresh Fruits","category_image":null,"category_description":null,"category_status":1,"show":0,"created_at":"2020-03-28T15:30:12.000000Z","updated_at":"2020-03-28T15:30:12.000000Z","deleted_at":null}},"quantity":1}" => null
]
]
i want to add id and total quantity shows last object into a table. table rows looks like this.
$table->increments('id');
$table->integer('order_id');
$table->integer('product_id')->unsigned();
$table->integer('total_quantity');
$table->timestamps();
$table->softDeletes();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
how can i write a store function using this data in laravel
result data looks like this
Array
(
[{"cart":] => Array
(
[{"product":{"id":1,"category":1,"product_name":"Brinjal 500g","product_image":"1585409454.jpeg","product_price":232,"unit":"500g","product_description":null,"stock":"In Stock","product_status":1,"show":1,"delievery_date":null,"vendor":null,"quantity":18,"item_type":"feature_product","created_at":"2020-03-28T15:30:54.000000Z","updated_at":"2020-03-28T15:30:54.000000Z","deleted_at":null,"categories":{"id":1,"category_name":"Fresh Fruits","category_image":null,"category_description":null,"category_status":1,"show":0,"created_at":"2020-03-28T15:30:12.000000Z","updated_at":"2020-03-28T15:30:12.000000Z","deleted_at":null}},"quantity":1}] =>
)
)
this is my latest update
$data = [];
foreach ($request->all() as $key => $value) {
$data[$key]['product_id'] = $value['product']['id'];
$data[$key]['quantity'] = $value['quantity'];
dd($value);
}
Loop through your data coming and make array as below i have shown.
Try this one by creating the array of the data and insert array to the database as bulk data:
// this will decode your json data that you're getting in the post data
$postdata = json_decode($request->all(), true);
$data = [];
foreach ($postdata as $key => $value) {
$data[$key]['product_id'] = $value['product']['id'];
$data[$key]['quantity'] = $value['quantity'];
}
// $data now will have data as following structure
$data = [[
'product_id' => 2,
'total_quantity' => 7
],
[
'product_id' => 2,
'total_quantity' => 7
]];
$order = Order::create($data);
This is my object $input:
$input = $this->em->getRepository(Data::class)->findAll();
foreach($input as &$arr){
$arr->{"Sunshine"} = 'Clouds';
}
The output of $input:
Data {#1523 ▼
-id: 23
-name: "cat"
-timestamp: DateTime #1570445917 {#1517 ▶}
+"Sunshine": "Clouds"
}
I am using serializer to create a JSON file $data
// Serialize your object in JSON
$context = [
'circular_reference_handler' => function ($object) {
return $object->getId();
},
'circular_reference_limit' => 0,
];
$data = $serializer->serialize($input, 'json', $context);
$data:
"[{"id":21,"name":"cat","timestamp":"07.10.2019"}] ◀"
I wonder, why "Sunshine" is not in the JSON file. Does it have something to do with the +? What does + mean?
I think you're assigning the key incorrectly. A key should be assigned like this:
$arr['keyName'] = $value
You're assigning it like this:
$arr->{"keyName"} = $value
I hope I helped you with this answer!
I'm using Laravel 5.7. and GuzzleHttp 6.0 to get API response
from endpoint
I'm passing query data from Blade form to this function.
public static function prhmulti($multisearch, $start ,$end)
{ $city = $multisearch['city'];
$client = new Client([
'base_uri' => 'https://avoindata.prh.fi/tr/',
'query' => [
'totalResults' => 'true',
'maxResults' => '1000',
'registeredOffice'=> $city,
'companyForm'=>'OY',
'companyRegistrationFrom'=>$start,
'companyRegistrationTo'=>$end,
],
'defaults'=>[
'timeout' => 2.0,
'cookies' => true,
'headers' => [
'content-type' => 'application/json',
'User-Agent' =>"GuzzleHttp/Laravel-App-5.7, Copyright MikroMike"
]]]);
$res = $client->request('GET','v1');
$ResData = json_decode($res->getBody()->getContents());
dd ($ResData) gives all data from API response.
But I am not able to return JSON back to other function
return $this->multisave($ResData);
public static function multisave (data $ResData)
This will parse JSON and
{
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
}
save data to Mysql.
$NewCompany = new Company();
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'street', $Addr],
[ 'postcode', $postcode],
[ 'city', $city],
[ 'regdate', $registrationDate],
]);
}
IF Parse part and Save part is inside same function code works ok(save only one company),
but I need to separate them because later on it's easier to maintain.
Error which I am getting to return $ResData
" Using $this when not in object context"
Information is in JSON array.
Also foreach part save ONLY one company ?
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
So : 1) What is best way to create own function for parse JSON
and other for save data to DB?
2) As foreach loop save only one company data, What is
best way to fix it?
Thanks MikroMike.
Resolved my own question for saving companies to db
First get total number inside Array
use for-loop to make counting
use foreach-loop extract information per single company as object.
$data = json_decode($res->getBody()->getContents());
$total = $data->totalResults;
for ($i = 0; $i < $total; $i++){
$NewCompany = new Company();
foreach ($data->results as $company)
{
$name = $company->name;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
$array = [];
Arr::set($array, 'vat_id', $businessId);
Arr::set($array, 'name', $name );
Arr::set($array, 'form', $companyForm);
Arr::set($array, 'regdate', $registrationDate);
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'regdate', $registrationDate],
]);
}// END OF MAIN FOREACH
}// END OF For loop
}// END OF FUCNTION
} // END OF CLASS
I'm having an issue rendering a Twig view and a JSON response, I need to call the twig view and pass it a new Json response with a variable as parameter. The output error is the following "Notice: Object of class Symfony\Component\HttpFoundation\Response could not be converted to int
"
Here is the code
$resultado = array('mes1_local' => $mes1_local, 'mes2_local' => $mes2_local, 'mes3_local' => $mes3_local, 'mes1_online' => $mes1_online, 'mes2_online' => $mes2_online, 'mes3_online' => $mes3_online, 'contador_pedido_local' => $contador_pedido_local, 'contador_pedido_online' => $contador_pedido_online, 'contador_total' => $contador_total, 'contador_usuarios' => $contador_usuarios);
return new JsonResponse($resultado, $this->render('others/adminlte.html.twig'));
Like #goto's answer, but it won't works, cause you need to use renderView instead of render:
return new JsonResponse([
'things' => $thingsArray,
'anotherVariable' => $simpleVariable,
'html' => $this->renderView('others/adminlte.html.twig', []/* template parameters goes here */),
]);
The Json Response signature is
__construct(mixed $data = null, int $status = 200, array $headers = array(), bool $json = false)
You are trying to give the twig to the status parameter.
You can avoid this silly error by using a good IDE
To give additional data to your response you could structure your array data returned
return new JsonResponse([
'someData' => $resultado,
'html' => $this->render('others/adminlte.html.twig')
);
I am using a calendar in my project and I want to pass data from my Event model to view file in JSON format. I tried following but it didn't work and am not able to display the data properly
$events = Event::find()->where(1)->all();
$data = [];
foreach ($events AS $model){
//Testing
$data['title'] = $time->title;
$data['date'] = $model->start_date;
$data['description'] = $time->description;
}
\Yii::$app->response->format = 'json';
echo \yii\helpers\Json::encode($data);
But it only returns one model in that $data array, the final data should be in following format:
[
{"date": "2013-03-19 17:30:00", "type": "meeting", "title": "Test Last Year" },
{ "date": "2013-03-23 17:30:00", "type": "meeting", "title": "Test Next Year" }
]
When you write this:
\Yii::$app->response->format = 'json';
before rendering data, there is no need to do any additional manipulations for converting array to JSON.
You just need to return (not echo) an array:
return $data;
An array will be automatically transformed to JSON.
Also it's better to use yii\web\Response::FORMAT_JSON constant instead of hardcoded string.
Another way of handling that will be using ContentNegotiator filter which has more options, allows setting of multiple actions, etc. Example for controller:
use yii\web\Response;
...
/**
* #inheritdoc
*/
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['view', 'index'], // in a controller
// if in a module, use the following IDs for user actions
// 'only' => ['user/view', 'user/index']
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
];
}
It can also be configured for whole application.
Update: If you are using it outside of controller, don't set response format. Using Json helper with encode() method should be enough. But there is also one error in your code, you should create new array element like this:
$data = [];
foreach ($events as $model) {
$data[] = [
'title' => $time->title,
'date' => $model->start_date,
'description' => $time->description,
];
}
You can try like this:
$events = Event::find()->select('title,date,description')->where(1)->all()
yii::$app->response->format = yii\web\Response::FORMAT_JSON; // Change response format on the fly
return $events; // return events it will automatically be converted in JSON because of the response format.
Btw you are overwriting $data variable in foreach loop you should do:
$data = [];
foreach ($events AS $model){
//Make a multidimensional array
$data[] = ['time' => $time->title,'date' => $model->start_date,'description' => $time->description];
}
echo \yii\helpers\Json::encode($data);