Laravel - How to insert multi-dimensional Array in DB - arrays

I have the array as below;
I'd like to insert each name keys into tableName and get the inserted id.
For the steps, each of them will be inserted into another table tableSteps including the last inserted id of the name.
Like as below screenshot.
In my controller,
Here's what I've done so far.
$instructionsArrays = $request->instructions;
$max = count($instructionsArrays);
for ($x = 1; $x <= $max; $x++) {
foreach($instructionsArrays as $instructionsArray){
Instruction::updateOrCreate(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $x],
['name' => $instructionsArray['name']],
);
}
}
I was able to save sequence numbers but for names it saves only the last name key.
And... I'm really lost..

You can achieve what you want from 2 for loops
foreach($request->instructions as $key => $val){
$id = Instruction::insertGetId(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],
['name' => $val['name']],
);
$data = []; //bulk insertion
$created_at = now();
foreach($val["steps"] as $step){
array_push($data, ["header_id" => $id, "name" => $step, "sequence" => $key+1, "created_at" => $created_at]); //why insert sequence when you can obtain it from the relationship?
}
Steps::insert($data);
}

With the help of the answer of #Kneegrows, I came up with the code below and it is now working. Thank you.
foreach ($request->instructions as $key => $val) {
$instruction = Instruction::updateOrCreate(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],
['instructions_name' => $val['name']],
);
$id = $instruction->id;
$data = []; //bulk insertion
$i = 1;
foreach ($val["steps"] as $step) {
if(!is_null($step)){
array_push($data, ["instruction_id" => $id, "steps_name" => $step, "sequence" => $i]);
$i++;
}
}
Steps::insert($data);
}

Related

Cant change single value in session array in Laravel

This my method update for products. And cant to change qty of product. Data saved inside foreach, but nothing change out of this. I can't understand what the problem.
if (!session()->has('products')) {
session()->put('products', []);
}
$products = session()->get('products');
foreach ($products as $item) {
if (isset($item[$product->id])) {
$item[$product->id]['qty'] = 10;
dd($products); // dd($item) - changes
$request->session()->put('products', $products);
return redirect()->back();
}
}
session()->push('products', [
$product->id => [
'product' => $product,
'qty' => 1
]
]);
return redirect()->back();
As you can see there is dd($products) - so its not change. But if dd($item) so it has qty 10.
I can solved this with next:
foreach ($products as $key => $value) {
if (isset($value[$product->id])) {
$value[$product->id]['qty'] = 10;
$products[$key] = $value;
$request->session()->put('products', $products);
return redirect()->back();
}
}
Just add a $key => $value and save it in $products[$key] = $value;

Add custom column in-between people/users admin page table drupal 7

I have created a custom column to display last user changed time, but I need this field to be insert before OPERATIONS column. Below is my code which append my custom field at the end.
function meme_user_update_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
$changed_column = array('changed' => array(
'data' => 'LAST CHANGED',
'field' => 'u.changed'
));
$form['accounts']['#header'] = $form['accounts']['#header'] + $changed_column;
foreach ($form['accounts']['#options'] as $key => $row) {
$user_object = user_load($key);
$user_language = ($user_object->language) ? $user_object->language : LANGUAGE_NONE;
$form['accounts']['#options'][$key]['changed'] = $user_object->field_user_changed[$user_language][0]['value'];
}
}
Found an answer, I think this might help someone.
function meme_user_update_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
$changed_column = array(
'data' => 'LAST CHANGED',
'field' => 'u.changed'
);
$operation_column = array_pop($form['accounts']['#header']);
$form['accounts']['#header']['changed'] = $changed_column;
$form['accounts']['#header']['operations'] = $operation_column;
foreach ($form['accounts']['#options'] as $key => $row) {
$user_object = user_load($key);
$user_language = ($user_object->language) ? $user_object->language : LANGUAGE_NONE;
$operation_column = array_pop($form['accounts']['#options'][$key]);
$form['accounts']['#options'][$key]['changed'] = $user_object->field_user_changed[$user_language][0]['value'];
$form['accounts']['#options'][$key]['operations']['data'] = $operation_column;
}
}

Why this code add only a single data from an array into a menu table

I am able to obtain the $data array from a form and I can generate data for each item... But during the binding and storing with jTable object it saves only the latest item why... I am using native JTableMenu class to bind and save by using my own class which is extended by native one. Early trials I used database object to save items with sql syntax but some columns of table remains empty lft and rgt to fill them I used table object but it gives this issue.
The whole code is following:
function addcumulative($data){
$db = JFactory::getDBO();
$component = & JComponentHelper::getComponent('com_dratransport');
$menus = array();
$query = array();
$countries = DraTransportHelperArrays::countries();
$cities = DraTransportHelperArrays::cities();
$title = array();
$alias = array();
$path = array();
$link = array();
if(empty($data['parent_id']) && $data['parent_id'] == 0){
$data['parent_id'] = 1;
}else{
$parent_id = explode('.',$data['parent_id']);
$data['parent_id'] = $parent_id[1];
}
if(!empty($data['locationQuery'])){ //actually this part will be used
$loc = ($data['locationQuery'] == 'countries') ? $countries : $cities['Turkey'] ;
foreach($loc as $k => $c){
$query[0] = $data['general'];
foreach($data as $key => $dat){
if(!empty($dat) && strpos($key,'Query') !== false){
$v = explode('Q',$key);
if($v[0] !== 'location'){
$query[] = '&'.$v[0].'='.$dat;
}else{
$query[] = '&'.$dat.'='.$k;
}
}
}
$title[] = $data['viewQuery'].'-'.$k;
$alias[] = $data['viewQuery'].'-'.$k;
$path[] = $data['viewQuery'].'-'.$k;
$link[] = implode('',$query);
$query = array();
}
}else{
$query[0] = $data['general'];
foreach($data as $key => $dat){
if(!empty($dat) && strpos($key,'Query') !== false){
$v = explode('Q',$key);
$query[] = '&'.$v[0].'='.$dat;
}
}
$link[] = implode('',$query);
}
foreach($link as $n => $l){
$menus[] = array(
'menutype' => $data['menutype'],
'title' => $title[$n],
'alias' => $alias[$n],
'path' => $path[$n],
'link' => $link[$n],
'type' => 'component',
'published' => 1,
'parent_id' => $data['parent_id'],
'level' => 1,
'component_id' => $component->id,
'access' => $data['access'],
'params' => $data['params'],
'language' => '*'
);
}
$count = $data['count'] == 0 ? count($loc) : $data['count'];
foreach($menus as $menu){
// Bind the data.
$table = $this->getTable();
$table->bind($menu);
$table->store();
}
}
Yes you are totally right. Let say $countries=array('England','France','Germany'); then I wrote my code in model to generate links in #__menu table. So I write
foreach($countries as $country){
$link='index.php&option=com_mycomponent&view=members&type=1&countries='.$country;
$table->bind();
$table->save();
}
I am generating links like this, view and the type values in query comes from the form submitted to make parmaters same for all menus except countries;
and I assign all parametes to manu item and menu items to an array as array item...
to save database the table comes with nested.
$menus->$each menu as $menus array item->menu item parameters
while the table is first created in above code code just adds the last menu item but if I take it insede the foreach it adds all of them but parent_id and level parameters assigned to 0 bye the native code altought I set them as 1

Codeigniter generate simple array from database

i have database with two values id and val so i want to ask how i can generate simple array like this
array('value', 'value2', 'value3'...);
I have
$query = $this->db->query('SELECT val FROM table');
echo $query->result_array();
But it will result something like that:
Array
(
[0] => Array
(
[val] => value
)
[1] => Array
(
[val] => value2
)
)
And i want it in one array so please if you can help me. Thanks for all answers :)
$query = $this->db->query('SELECT val FROM table')->result_array();
$array = array();
foreach ( $query as $key => $val )
{
$temp = array_values($val);
$array[] = $temp[0];
}
See it here in action: http://viper-7.com/tPd7zN

How to save values of an array to a table?

I have these codes on my add view
$status = array('0' => 'Resolved', '1' => 'Assigned/Unresolved', '2' => 'Suspended', '3' => 'Closed', '4' => 'Bypassed');
echo $this->Form->input('status', array('options' => $status));
and instead of saving the value (e.g. Resolved) to the table, it saves the index of the array. Any ideas?
You should do something like this:
$status = array('resolved' => 'Resolved', 'assigned' => 'Assigned/Unresolved'...);
It saves the index of the array. But this is not a good practice, instead try using enums. Check this out:
/**
* Get Enum Values
* Snippet v0.1.3
* http://cakeforge.org/snippet/detail.php?type=snippet&id=112
*
* Gets the enum values for MySQL 4 and 5 to use in selectTag()
*/
function getEnumValues($columnName=null, $respectDefault=false)
{
if ($columnName==null) { return array(); } //no field specified
//Get the name of the table
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$tableName = $db->fullTableName($this, false);
//Get the values for the specified column (database and version specific, needs testing)
$result = $this->query("SHOW COLUMNS FROM {$tableName} LIKE '{$columnName}'");
//figure out where in the result our Types are (this varies between mysql versions)
$types = null;
if ( isset( $result[0]['COLUMNS']['Type'] ) ) { $types = $result[0]['COLUMNS']['Type']; $default = $result[0]['COLUMNS']['Default']; } //MySQL 5
elseif ( isset( $result[0][0]['Type'] ) ) { $types = $result[0][0]['Type']; $default = $result[0][0]['Default']; } //MySQL 4
else { return array(); } //types return not accounted for
//Get the values
$values = explode("','", preg_replace("/(enum)\('(.+?)'\)/","\\2", $types) );
if($respectDefault){
$assoc_values = array("$default"=>Inflector::humanize($default));
foreach ( $values as $value ) {
if($value==$default){ continue; }
$assoc_values[$value] = Inflector::humanize($value);
}
}
else{
$assoc_values = array();
foreach ( $values as $value ) {
$assoc_values[$value] = Inflector::humanize($value);
}
}
return $assoc_values;
} //end getEnumValues
Paste that method in your AppModel.
Create the column in your table as an enum with the posible values, and use that method to get them.
Can you not define the index as the value you want?
$status = array('Resolved' => 'Resolved', 'Assigned/Unresolved' => 'Assigned/Unresolved', etc etc );
echo $this->Form->input('status', array('options' => $status));

Resources