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();
Related
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'.
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);
Using Laravel5.1 ...
I'm trying to convert this JSON:
"[{"John Doe":"john.gmail.com"},{"Frank Smith":"frank#frank.com"},{"Jie Brent":"jie#gmail.com"},{"Jeffrey Manney":"jeff17#gmail.com"}]"
To this:
"[{"name":"John Doe", "email":"john.gmail.com"},{"name":"Frank Smith", "email":"frank#frank.com"},{"name":"Jie Brent", "email":"jie#gmail.com"},{"name":"Jeffrey Manney", "email":"jeff17#gmail.com"}]"
This is my code:
$users_storage = [];
foreach($rcf_and_rcfm_users as $key => $user){
$users_storage[][$key] = $user;
}
$users = json_encode($users_storage);
dd($users);
The $rcf_and_rcfm_users variable is a collection of users from the database.
If I understand it correctly.
$users_storage = [];
foreach($rcf_and_rcfm_users as $name => $email){
$users_storage[] = [
'name' => $name,
'email' => $email,
];
}
$users = json_encode($users_storage);
dd($users);
I think this is what you're trying to accomplish.
I have a Symfony3 Application setup and would like to rebuild the frontend based on React now.
One of the Entities is User and each of them can have one or more Groups so in the HTML form a list of Checkboxes appears, so the admin can select the groups attached to a User.
In UserType.php this looks like that:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', TextType::class)
->add('password', TextType::class)
->add('email', EmailType::class)
->add('groups', EntityType::class, [
'class' => Group::class,
'choice_label' => 'name',
'expanded' => true,
'multiple' => true//,
//'data' => $builder->getData()->getGroups()
]);
}
To render the Form using React, it would be extremely handy to get a JSON response which could look like that:
{
"user": {
…
"groups": [<gid 1>, …]
"groups_available": [
{
"id": <gid 1>,
"name": …
},
…
]
}
}
So that the groups array contains all the ids of the groups, the user is attached to and groups_available a list of all available groups.
Right now I am using FOSRestBundle and in the Controller it looks like that:
public function getUserformAction($id=null)
{
//if the id is null, create a new user
//else get the existing one
…
$form = $this->createForm(UserType::class, $user);
$view = $form->createView();
return $this->handleView($view);
}
How can I do that?
you should try the following code:
->add('groups', EntityType::class, array(
//if Group is in AppBundle or use the required Bundle name
'class' => 'AppBundle:Group',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.name', 'ASC')
},
'choice_label' => 'name',
'multiple' => true,
'expanded' => true,
));
You can also get a reference from here
After digging in the source and with the help of the debugger I could manage to do it in a more less robust and generic way like so:
protected function getFormStructure(Form $form)
{
return $this->iterateFormview($form->createView(), []);
}
private function iterateFormview(FormView $view, array $result)
{
foreach($view as $child) {
$vars = $child->vars;
$data = ['value' => $vars['value']];
if(isset($vars['choices'])) {
$data['choices'] = [];
foreach ($vars['choices'] as $choice) {
array_push($data['choices'], [
'label' => $choice->label,
'value' => $choice->value]);
}
}
$result[$vars['full_name']] = $data;
if(count($child) > 0) {
$result = $this->iterateFormview($child, $result);
}
}
return $result;
}
Result (as json):
{
…
"user[groups]":
{
"value": "",
"choices": [
{
"value": 100,
"label": "the name"
},
…
]
}
}
I guess this routine needs to be extended if I need to support more types… But for now this will do it.
Hi, my problem is simple i want to add multiple where condition on yii2 Query bulder, but i don't know what doing.
my code like that
public function searchForTrip($params, $extraParams, $filter) {
$query = Boatinformation::find()
->where(['what_island' => $params['BoatinformationSearch']['what_island']])
->all();
if(isset($filter)) {
foreach ($filter as $key => $value) {
->andFilterWhere([$value => 1])
}
}
return $query;
}
this is not working
please someone help me
You can do in several way and you can found an useful guide in this doc http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html
you can use string format specifying the condition as a string :
$query->where('your_field1 =1 and your_field2 = 2');
You can use hash format and
$query->where([
'your_field1' => 10,
'your_field2' => null,
'your_field3' => [4, 8, 15],
]);
You can use operator format
$query->where(['and' , 'your_field1', 10, ]);
and you can also use
andWhere('your_field'=> $your_value ),
You should write something like
public function searchForTrip($params, $extraParams, $filter) {
$query = Boatinformation::find()
->where(['what_island' => $params['BoatinformationSearch']['what_island']])
if(isset($filter)) {
foreach ($filter as $key => $value) {
$query->andFilterWhere([$value => 1])
}
}
return $query;
}
$query->andFilterWhere() add where condition if $value exist,
$query->andWhere() add where condition always
and if you want to return objects instead of query you should return $query->all();