Inserting multipe rows from dynamic form fields using laravel 5 - laravel

How can I store multiple form array data in laravel, as I need to create a new record against each array index.
[0] => Array
(
[make] => test
[model] => XYZ
)
[1] => Array
(
[make] => s4
[model] => BB
)
[2] => Array
(
[make] => 99
[model] => AX
)
This is what I am trying to, but here loop get executed 6 times instead of three
$results = $request->all();
foreach ($results as $key => $value) {
echo $key;
// insert operation
}

I believe you should specify the control/field because the Request contains other (non-data) information. Something like:
$results = $request['array_name'];

https://laravel.com/docs/5.4/queries#inserts
Model::insert($request->all())
This will mass insert each array into your database. insert do not automatically set datetime values for created_at and updated_at, note that the array keys should match your table columns, and make sure your model has these fields as $fillables.

Related

How to update multiple rows sharing same foreign key in Codeigniter

I have 2 tables; db_file_acess and db_file_access_details. I have a column subjects_id in db_file_access_details table. From the UI, I can select several subjects[array] with other details and insert them to db_file_acess table, and subject_ids to the db_file_access_details. Insertion is OK but when I update the two tables, I can't seem to update all the rows. This is my update query
$result = array();
foreach ($subject_id as $key => $val) {
$result[] = array(
'file_access_id' =>$q_id,
'subjects_id' => $_POST['subject_id'][$key]
);
}
$this->db->update_batch('db_file_access_details', $result, 'file_access_id');
The query runs but it updates with only one id as seen in the screenshot below:
the result() array is as shared below:
Array
(
[0] => Array
(
[file_access_id] => 45
[subjects_id] => 1
)
[1] => Array
(
[file_access_id] => 45
[subjects_id] => 3
)
[2] => Array
(
[file_access_id] => 45
[subjects_id] => 4
)
)
after update_batch query, the resultant results is as shown below
What am I doing wrong?
According to the docs update_batch('db_file_access_details', $result, 'file_access_id') produces:
UPDATE `db_file_access_details` SET `subjects_id` = CASE
WHEN `file_access_id` = 45 THEN 1
WHEN `file_access_id` = 45 THEN 3
WHEN `file_access_id` = 45 THEN 4
ELSE `subjects_id` END
WHERE `file_access_id` IN (45, 45, 45)
For all three rows, the first case matches, so all subject_ids are set to 1.
For update_batch to work correctly you need to use the id column.
Depending on what you want to achieve, you could also consider deleting all rows for the file_access_id in db_file_access_details and then inserting the $result array with insert_batch instead.

How to Sort Laravel collection groupBy results in asc order

I am just running a query in Laravel using a query builder as follows.
$query = \DB::table('units_amenities_values')
->join('units', 'units.id', 'units_amenities_values.unit_id')
->join('floors', 'floors.id', 'units.floor_id')
->join('buildings', 'buildings.id', 'floors.building_id')
->join('properties', 'properties.id', 'buildings.property_id')
->leftJoin('amenity_values', 'amenity_values.id', 'units_amenities_values.amenity_value_id')
->leftJoin('amenities', 'amenities.id', 'amenity_values.amenity_id')
->select('units_amenities_values.id as uav_id', 'amenities.id as amenity_id', 'amenities.amenity_name', 'amenity_values.amenity_value', 'floors.floor','units.id as unit_id', 'units.unit_number','units.unit_rent', 'units.stack', 'amenities.category_id', 'buildings.id as building_id')
->where('buildings.property_id',2)
->orderBy('units.unit_number','asc');
$data = $query->get();
$grouped = $data->groupBy('building_id');
This works without error, however, the result is not in the way as I intended. This is grouping in descending order.
I tried by adding ->orderBy('buildings.id','asc') before as well as after orderBy('units.unit_number','asc'). This makes does not make any difference. Also, tried by adding orderBy('building_id','asc') with groupBy as well, but it throws error as orderBy does not exist.
Is there anything that I could do, to get the results as my preference.
By the way, the $grouped looks like:
<pre>Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[7] => Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[uav_id] => 5557
...
...
[building_id] => 7
)
[1] => ...
[2] => ...
)
)
[6] => ...
[5] => ...
[4] => ...
...
)
)
</pre>
As you have given several examples I'm not sure what order you want the results in. Do you want the results ordered by buildings_id, or unit_number or both?
The query you have shown will order the results by unit_number (although you have failed to show this value in you output).
The ->groupBy() method takes the building_id from your results and creates a new key - but doesn't reorder your collection, so it's still ordered by unit_number.
If you want to return a collection ordered by building_id, use ->orderBy('building_id', 'asc') which will return an ordered collection. If you iterate through it, it will be in the correct order.
If you prefer a plain array, use
$array = $data->toArray()
If you want to keep the grouping (with the extra key), then use
$grouped = $data->sortBy('building_id')->groupBy('building_id')

How to insert the array values in database using for each loop

I have array i want insert into the values in database using codeigniter, i don't know how to insert , i trying but i am not able to get the answer
My model
print_r($subjectHandling);
Array
(
[subjectId] => Array
(
[0] => 1
[1] => 2
)
)
now i want insert the values in database in this values.
I am trying like this
foreach($subjectHandling as $key=>$value) {
$reg_dat = array(
'statffId' => '1',
'subjectId' => $value,
);
$this->db->insert("subject_handling" , $reg_dat);
}
I m getting error ** Array to string conversion** , so how do this. i want to insert two roes in databse
This should work
$subjectHandling['subjectId'] = array(1, 2);
$reg_dat = array();
foreach($subjectHandling['subjectId'] as $key => $value) {
$reg_dat[] = array('staffId'=> 1, 'subjectId' => $value);
}
$this->db->insert_batch('subject_handling', $reg_dat);
https://www.codeigniter.com/userguide3/database/query_builder.html#inserting-data

codeigniter form_validation is_unique compare data between tables

I have a from which lists several items that can be selected by check box and a dropdown permitter added. In a separate part of the form is have another check box. This is submitted as two arrays.
The arrays look like this
Array
(
[1] => Array
(
[num_copy] => 1
[dwg_rev] => B
[dwg_id] => 1
)
[2] => Array
(
[num_copy] => 1
[dwg_rev] => B
[dwg_id] => 2
)
)
Array
(
[1] => Array
(
[client_id] => 1
)
)
I need to pass these two arrays to a form_validation that can check is dwg_rev has already been added to the database for the selected client_id.
I tried to use is_unique, but it can only check in one table to see if this already exists in it.
This is what my form validation currently looks like
$rows = array();
if(!empty($_POST['result']))
{
$rows = $_POST['result'];
$temp_dwg_array = array_column($rows, 'temp_dwg_id');
foreach($temp_dwg_array as $key => $temp_dwg_id)
{
$this->form_validation->set_rules('result['.$temp_dwg_id.'][dwg_rev]', 'Revision' , 'required|callback_check_issued_rev');
}
} else $this->form_validation->set_rules('result[][temp_dwg_rev]', 'Revision' , 'required');
if(!empty($_POST['client']))
{
$temp_client_array = array_column($_POST['client'],'client_id');
foreach($temp_client_array as $key => $client_id)
{
$this->form_validation->set_rules('client['.$client_id.'][client_id]', 'Please make a selection from the distribution list' , 'required|callback_check_issued_rev');
}
}
else $this->form_validation->set_rules('client[][client_id]', 'Distribution' , 'required');
I want to create a callback function, but I can't figure out how to pass two variables to the callback function to compare to the db.

multidimensional array

What is the meaning of the following line:
$data[0][$row->parentid]['children'][$row->id] = $row->name
From the function:
function getCategoriesNav(){
$data = array();
$this->db->select('id,name,parentid');
$this->db->where('status', 'active');
$this->db->orderby('parentid','asc');
$this->db->orderby('name','asc');
$this->db->groupby('parentid,id');
$Q = $this->db->get('categories');
if ($Q->num_rows() > 0){
foreach ($Q->result() as $row){
if ($row->parentid > 0){
$data[0][$row->parentid]['children'][$row->id] = $row->name;
}
else{
$data[0][$row->id]['name'] = $row->name;
}
}
}
$Q->free_result();
return $data;
}
Where do the children come from, and what is the meaning of:
$row->parentid or $row->name? I don't have any field 'children' in my table, and it's not declared any where. Please help
Thank you in advance,
Mehdy
Update
Sorry if I didn’t explain the question clearly. My question was: what is the meaning of the following line in this function
$data[0][$row->parentid]['children'][$row->id] = $row->name, from where this children come from, and what actual mean by $row->parentid or $row->name? I don’t have any field 'children' in my table, and it’s not declared anywhere, please help me.
Thank you
mehdy
Read the code. If the row from categories has a parent ID, child IDs are added to the array under the parent ID's children element. This is simply taking the result set and converting it into a hierarchy data structure which eliminates repetition in places and makes it easier to traverse.
Update:
Specifically, what is the following line of code doing:
$data[0][$row->parentid]['children'][$row->id] = $row->name;
Your function is looping through your query result set and checking if the current row specifies a parent ID. If it does it append a hash to your array of arrays (your hierarchy).
foreach ($Q->result() as $row) {
Your query result is a collection of row objects. Each object appears to have an attribute for each column being selected in your SQL query. So for your SELECT fields:
$this->db->select('id,name,parentid');
We have:
$row->id
$row->name
$row->parentid
Going back to the original line of code:
$data[0][$row->parentid]['children'][$row->id] = $row->name;
This line is constructing a structure like this:
Array (
[0] => Array ( // $data[0]
[400] => Array ( // $data[0][$row->parentid]
[children] => Array ( // $data[0][$row->parentid]['children']
[53] => Animal // these are from [$row->id] = $row->name;
[54] => Mineral
[55] => Vegetable
)
)
[401] => Array (
[children] => Array (
[4] => Wood
[6] => Metal
[2] => Plastic
)
)
)
)
You could simplify this structure slightly by removing the first wrapper array $data[0]. So you'd change the code like so:
$data[$row->parentid]['children'][$row->id] = $row->name;
This changes the structure like so:
Array (
[400] => Array ( // $data[$row->parentid]
[children] => Array ( // $data[$row->parentid]['children']
[53] => Animal // these are from [$row->id] = $row->name;
[54] => Mineral
[55] => Vegetable
)
)
[401] => Array (
[children] => Array (
[4] => Wood
[6] => Metal
[2] => Plastic
)
)
)
I hope this clarifies the code for you.
It add a value in a array namely $row->name with the ID $row->id
So what it does is adding a child row to the parent with the ID that is in $row->parentid at that moment. It loops through the loop and add child's to the parent if the parent has child's

Resources