"message": "Illegal string offset 'product_id'", In Laravel RESTfull API - json

Am developing Laravel RESTful API for saving array of Json object into DB using php associative array and this is the error am getting.;
"message": "Illegal string offset 'product_id'",
"exception": "ErrorException",
...
This is the array of JSON object am trying to save in Mysql DB
"userId": "1",
"userName": "Dan",
"userEmail": "dan#gmail.com"
"product": [
{
"product_id": "31",
"product_name": "Orange",
"product_price": "USD 0.5"
}
]
}
This is the php function for save Json object into DB.
$userId = $request -> input('userId');
$userName = $request ->input('userName');
$userEmail = $request ->input('userEmail');
$data = array(
"userId"=>$userId,
"userName"=>$userName,
"userEmail"=>$userEmail
);
$user = User::create($data);
if($order){
//Storing the received JSON in $json.
$json = file_get_contents('php://input');
// Decode the received JSON and store into $obj
$obj = json_decode($json,true);
foreach($obj as $product){
$product_id = $product['product_id'];
$product_name = $product['product_name'];
$product_price = $product['product_price'];
$product = array(
"product_id" => $product_id,
"product_name" => $product_name,
"product_price" => $product_price
);
DB::table('products')->insert($product);
}
if($product){
// On query success it will print below message.
$MSG = 'Data Successfully Submitted.' ;
// Converting the message into JSON format.
$json = json_encode($MSG);
// Echo the message.
echo $json ;
}
else{
echo 'Try Again';
}
Guys where am I making mistake. Thank you in advance!

Related

Powershell Convert to JSON

I want to convert the data in the following script to JSON, can anyone let me know how to include [] in the JSON using powershell.
My script:
$URL = " http://localhost:4200/api/testinglabproject/test-run"
$projectShortName = "NES"
$testPlanName = "TestManager"
$deviceName = "testt"
$nodeManagerResourceName = "nm-4c2f1575-00fd-4363-b88a-2fb3cf587223"
$hostname = "DSTW8Y2.bla.is.abc.com"
$resourceName = "hs-515a8129-1aa0-4a14-847b-210022fe9cd7"
$hardwareSolutionType = "testt"
$emailId = "abc#gmail.com"
$data = #{
projectShortName=$projectShortName
testPlanName=$testPlanName
hardwareSolution=#{
hardwareSolutionItemList =
#{deviceName = $deviceName
nodeManagerResourceName =$nodeManagerResourceName
hostname = $hostname}
hardwareSolutionMetadataList = "[]"
resourceName = $resourceName
hardwareSolutionType = $hardwareSolutionType
}
emailId = $emailId
}
$jsondata = $data | ConvertTo-Json -Depth 3
Write-Host $jsondata
The resulting JSON should be like this:
{
"projectShortName": <projectShortName>,
"testPlanName": <planName>,
"hardwareSolution": {
"hardwareSolutionItemList": [{"deviceName": <deviceName>,
"nodeManagerResourceName": <NodeManagerResourceName>,
"hostname": <hostName>}],
"hardwareSolutionMetadataList": [],
"resourceName": <HardwareSolutionResourceName>,
"hardwareSolutionType": <hwstName>
},
"emailId": <emailID>
}
I stripped all those superfluous variables and replaced the string "[]" with an actual PowerShell array #() for the hardwareSolutionMetadataList key:
$data = #{
testPlanName = "TestManager"
projectShortName = "NES"
hardwareSolution = #{
hardwareSolutionItemList = #{
deviceName = "testt"
nodeManagerResourceName = "nm-4c2f1575-00fd-4363-b88a-2fb3cf587223"
hostname = "DSTW8Y2.bla.is.abc.com"
}
hardwareSolutionMetadataList = #()
resourceName = "hs-515a8129-1aa0-4a14-847b-210022fe9cd7"
hardwareSolutionType = "testt"
}
emailId = "abc#gmail.com"
}
$jsondata = $data | ConvertTo-Json -Depth 3
Write-Host $jsondata
PowerShell's idea of JSON formatting is a bit odd, but structurally it's OK.
{
"hardwareSolution": {
"hardwareSolutionItemList": {
"deviceName": "testt",
"hostname": "DSTW8Y2.bla.is.abc.com",
"nodeManagerResourceName": "nm-4c2f1575-00fd-4363-b88a-2fb3cf587223"
},
"resourceName": "hs-515a8129-1aa0-4a14-847b-210022fe9cd7",
"hardwareSolutionMetadataList": [
],
"hardwareSolutionType": "testt"
},
"testPlanName": "TestManager",
"emailId": "abc#gmail.com",
"projectShortName": "NES"
}
You can use the -Compress parameter to remove the whitespace for uploading the JSON somewhere.
{"hardwareSolution":{"hardwareSolutionItemList":{"deviceName":"testt","hostname":"DSTW8Y2.bla.is.abc.com","nodeManagerResourceName":"nm-4c2f1575-00fd-4363-b88a-2fb3cf587223"},"resourceName":"hs-515a8129-1aa0-4a14-847b-210022fe9cd7","hardwareSolutionMetadataList":[],"hardwareSolutionType":"testt"},"testPlanName":"TestManager","emailId":"abc#gmail.com","projectShortName":"NES"}

how to convert array from postgres db to array variable in laravel?

how to convert array from postgres db to array variable in laravel ?
my postgres array structure
i have result var_dump from laravel :
0 => array:1 [
"order_itemset" => "{8,11}"
]
1 => array:1 [
"order_itemset" => "{8,12}"
]
2 => array:1 [
"order_itemset" => "{17,10}"
]
]
how i can get the data and store the data to array variable?
like this
$data = [['8', '11'], ['8', '12'], ['17', '10']];
sorry for my broken english ,thanks.
Take a look here.
You can simplify this code if your postgres query returns an array "[8,11]" instead of a "sort-of" JSON "{8,11}"
<?php
$values = array_column($your_data, 'order_itemset');
$values = array_map(function ($v) {
preg_match("/^\{(.+)\}$/", $v, $matches);
if ($matches[1]) {
return explode(',', $matches[1]);
}
return null;
}, $values);
print_r($values);
you can use foreach
$original_array = $your_array; //Your base array that you showed us on your Question
$base_array = array();
foreach($original_array as $original)
{
$child_array = array();
foreach($original->order_itemset as $a)
{
$child_array[] = $a;
}
$base_array[] = $child_array;
unset($child_array);
}
die($base_array);

Api Response and Json laravel format

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

Post PowerShell JSON into ElasticSearch

I'm trying to push some data into ElasticSearch via PowerShell. I'm converting the data into JSON, then trying both Invoke-WebRequest and Invoke-RestMethod, but always get errors on malformed data or content-type not supported. I haven't created the index as I believe it will create it for me.
Anyone able to assist on what I'm missing/doing wrong?
Example code:
$data = #()
$CustomObject = [pscustomobject]#{
SqlInstance = "myserver1"
Database = "mydb"
Schema = "versioning"
Name = "DataVersionHistory"
IndexSpaceUsed = 0
DataSpaceUsed = 0
RowCount = 0
};
$data += $CustomObject;
$CustomObject = [pscustomobject]#{
SqlInstance = "myserver1"
Database = "mydb"
Schema = "versioning"
Name = "VersionHistory"
IndexSpaceUsed = 10
DataSpaceUsed = 25
RowCount = 3000
};
$data += $CustomObject;
$myJson = ConvertTo-Json -InputObject $data ;
Invoke-RestMethod -Uri http://localhost:9200/myindex/mytype/_bulk?pretty `
-Method POST -Body $myJson -ContentType "application/json"
Bulk request is not actual json. You should use following notation:
curl -XPOST 'localhost:9200/_bulk?pretty' -H 'Content-Type: application/json' -d'
{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }
{ "field1" : "value1" }
{ "delete" : { "_index" : "test", "_type" : "type1", "_id" : "2" } }
{ "create" : { "_index" : "test", "_type" : "type1", "_id" : "3" } }
{ "field1" : "value3" }
{ "update" : {"_id" : "1", "_type" : "type1", "_index" : "test"} }
{ "doc" : {"field2" : "value2"} }
'
$data = #()
$CustomObject = [pscustomobject]#{
SqlInstance = "myserver1"
Database = "mydb"
Schema = "versioning"
Name = "DataVersionHistory"
IndexSpaceUsed = 0
DataSpaceUsed = 0
RowCount = 0
};
$data += $CustomObject;
$CustomObject = [pscustomobject]#{
SqlInstance = "myserver1"
Database = "mydb"
Schema = "versioning"
Name = "VersionHistory"
IndexSpaceUsed = 10
DataSpaceUsed = 25
RowCount = 3000
};
$data += $CustomObject
At this point you have a collection of objects contained in the array $data.
NOTE: for the bulk API the final line of the json data must end with a newline character \n. So I am using a here-string to append the newline char \n to each json element.
also notice that i removed pretty print. this is to play nice with the bulk api.
doc_as_upsert ensures that if the doc exists leave it alone, if not add as new.
$json_col = #()
$data |
ForEach-Object {
#convert object to json
$json_element = #{doc = $_; doc_as_upsert = $true}
| ConvertTo-Json -Depth 1 -Compress
#construt here string with literal \n
$json_col += #"
$json_element\n
"#
}
Invoke-RestMethod -Method Post -Uri "http://localhost:9200/myindex/mytype/_bulk?" -Body $json_col -ErrorAction Stop

How to create associative array in Yii2 and convert to JSON?

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