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);
Related
The problem I am facing in the api is as follows: it is not accepting array of multiple arrays:
...
"message": "Array to string conversion",
"exception": "ErrorException",
"file": "/home/deepan8/pich.abc.com/vendor/laravel/framework/src/Illuminate/Support/Str.php",
"line": 762,
"trace": [
{
"file": "/home/deepan8/pich.abc.com/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php",
"line": 257,
"function": "handleError",
"class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
"type": "->"
},]
My code snippet looks like this:
$voucherArray = [];
foreach($users as $user) {
$voucherArray[] = ['voucher_code' => rand(10000, 999999),
'voucher_price' => $request->price,
'expiry_date' => $request->date,
'status' => "Active",
];
}
$ids = DB::table('pich_voucher')->insertGetId($voucherArray);
foreach($ids as $id) {
}
I need to add all the rows at once instead of adding them one by one to improve performance.
Does Laravel have some function which can provide this facility or any SQL Query where we can add multiple rows and extract their ids at the same time?
You can insert multiple rows using insertGetId() method. If you want really want to insert multiple rows and get the IDs, just use looping.
example:
$ids = [];
foreach ($users as $user) {
$voucherArray = array(
'voucher_code' => rand(10000, 999999),
'voucher_price' => $request->price,
'expiry_date' => $request->date,
'status' => "Active"
);
$ids[] = DB::table('pich_voucher')->insertGetId($voucherArray);
}
Or another way use insert method but not get the ids. if you want to get the ids you could use like below:
$voucherArray = [];
$codes = [];
foreach ($users as $user) {
$code= rand(10000, 999999);
$codes[] = $code;
$voucherArray[] = array(
'voucher_code' => $code,
'voucher_price' => $request->price,
'expiry_date' => $request->date,
'status' => "Active"
);
}
DB::table('pich_voucher')->insert($voucherArray);
$ids = DB::table('pich_voucher')->whereIn('voucher_code', $codes)->pluck('id')->toArray();
I want to retrieve some data from 'tbl_karyawan' and input into 'tbl_absen' which is if the NIP exist from 'tbl_karyawan' then parshing some data into 'tbl_absen'. I was create the code, and the data is going well. but i have something trouble with
i want the data input in Nip_kyn be like 'KIP001' not [{"Nip_kyn":"KIP001"}].
this is my Model
public function presensi($data)
{
$isExist = DB::table('tbl_karyawan')
->where('Nip_kyn', $data)->exists();
if ($isExist) {
$namakyn = DB::table('tbl_karyawan')->where($data)->get('Nama_kyn');
$nippppp = DB::table('tbl_karyawan')->where($data)->select('Nip_kyn')->get($data);
$values = array('Nip_kyn' => $nippppp, 'Nama_kyn' => $namakyn, 'Jam_msk' => now(), 'Log_date' => today());
DB::table('tbl_absen')->insert($values);
} else {
echo 'data not available';
}
}
this is my controller
public function get()
{
$day = [
'time_in' => $this->AbsenModel->timeIN(),
'time_out' => $this->AbsenModel->timeOut(),
'break' => $this->AbsenModel->break(),
// absen here
's' => $this->AbsenModel->absensi(),
];
$data = [
'Nip_kyn' => Request()->Nip_kyn,
];
$this->AbsenModel->presensi($data);
return view('v_absen', $data, $day);
}
Yup, I finally got it, the problem is on my model.
$nama_karyawan = DB::table('tbl_karyawan')->where($data)->value('Nama_kyn');
$nipkyn = DB::table('tbl_karyawan')->where($data)->value('Nip_kyn');
I just change 'get' to 'value'.
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);
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
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);