Undefined offset: 1, getting this error in looping - html

I have the following code:
$datas = $request->all();
if (!empty($datas)){
for ($i=1; $i<count($datas); $i++){
$value = [
'questionnaire_id' => $datas[$i]->questionnaires_id,
'question_id' => $datas[$i]->id,
'answer' => $datas[$i]->key
];
return $value;
}
}
I am getting error:
Undefined offset: 1
With input form:
<input type="" name="{{$question->id}}" value="{{$key}}">
How can I receive this value in controller?

You're assuming that $datas is a numerical array starting at index 1 with no gaps. That may not be the best assumption.
Based on my knowledge of request()->all(), it's going to return an associative array of all your user input so you wouldn't be able to access an $i key on $datas. Just because it may have 1 element, doesn't mean that index on the array will be 1.
Perhaps you want to retrieve a specific user input, for example, if you had a checkbox named checkbox, you may want to use request()->input('checkbox') instead of request()->all(), but I'd still assume your array keys would start from 0 and not 1.
When all else fails, set a breakpoint and use a debugger to see the value of $datas. If you don't have a debugger (which I highly recommend) you can use dd($datas); to die and dump the value.

You could try initialize the variable i = 0. Also make a dd($datas) to see what you are evaluating.
$datas = $request->all();
if (!empty($datas)){
for ($i=0; $i<count($datas); $i++){
$value = [
'questionnaire_id' =$datas[$i]->questionnaires_id,
'question_id' =$datas[$i]->id,
'answer' =$datas[$i]->key
];
return $value;
}
}

Related

How do I make the most effective and efficient logic to check the data in the database exist or not?

I use laravel 5.6
I have a json file containing 500 thousand records. I want to create a logic to check whether the id of each record already exists or not in the database. If it doesn't already exist, then there will be a data insert process. If it already exists, there will be a data update process
I have made logic. I just want to make sure whether my logic is effective or not
My logic code like this :
$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
$data = \DB::table('details')->where('id', '=', $value['Code'])->get();
if ($data->isEmpty()) {
\DB::table('details')->insert(
[
'id' => $value['Code'],
'number' => $value['Number'],
...
]
);
}
else {
\DB::table('details')
->where('id', '=', $value['Code'])
->update([
'id' => $value['Code'],
'number' => $value['Number'],
...
]);
}
}
The code is working. But the process seems really long
Do you have another solution that is better?
updateOrCreate
You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model, so there's no need to call save():
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
in your case your code should be like this (create Details model first) :
$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
Details::updateOrCreate(
[ 'id' => $value['Code'] ],
[ 'number' => $value['Number'], ... ]
);
}
i think that's the best way to do it. Eloquent return's a collection so you cant just validate that your string is null.

How to get all all key values of an array in laravel?

I am not getting all the key values of and array using foreach, its giving only first key value.
$order_id = DB::table('order')->where('delivery_boy_id', $delivery_boy_id)->where('is_accept', 1)->whereRaw('delivery_completed_at < time_of_assignment')->get();
When i run this code i get two key value
array:2 [0 => {#325
+"id": 37
+"order_id": 8261
+"delivery_boy_id": 8}1 => {#326
+"id": 38
+"order_id": 8261
+"delivery_boy_id": 8]
After using this json response i am getting the response of only one key value
foreach($order_id as $value){ $values = $value) };
$this->response['items'] = $order_id;
return json_encode($this->response);
check this
$order_id = DB::table('order')->where('delivery_boy_id', $delivery_boy_id)->where('is_accept', 1)->whereRaw('delivery_completed_at < time_of_assignment')->get();
// return $order_id;(returns json array)
$data = [];
foreach($order_id as $order)
{
var_dump($order);
//in first loop first array will come
//second loop second array
$data[]=[
'id' => $order['id'],
'..' => '..'
];
}
return $data;
}
Dd means dump and die so it stops execution. If you dd in a for each loop, you will only get the current value in the loop (I.e the first one) because it will halt execution and you will never reach the second loop through. Use var_dump to allow execution to continue and dump variables.
If you simply want to return the Json to the user, you can just return the result of your query as laravel handles serialisation for you. You don't need to loop over the result. See the docs:
https://laravel.com/docs/5.1/eloquent-serialization
You are overwriting $values in your loop. So every time it passes through the for each loop, it overwrites $values with the current $value so it will only ever contain 1 object. You don't need to do the serialisation manually, use the laravel helper methods
Also in your code snippet you are looping over $order, but the result of your query is assigned to $order_id? I'm assuming that's due to abbreviating your code

EntityMetadataWrapperException: Invalid data value given when setting file field

Cannot set file_field in field_collection
Has node $order and field_collection called field_blueprints:
<?php
$entity_type = "field_collection_item";
$blueprint_obj = entity_create($entity_type, array('field_name' => "field_blueprints") );
$blueprint_obj->setHostEntity('node', $order);
$blueprint_entity = entity_metadata_wrapper($entity_type, $blueprint_obj);
date_default_timezone_set("UTC");
$blueprint_entity->field_blueprint_file->file->set((array)$file);
$blueprint_entity->field_blueprint_comment = (string) $file->filename;
$blueprint_obj->save();
node_save($order);
And this code throws error:
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityDrupalWrapper->set() (line 736 of sites//all/modules/entity/includes/entity.wrapper.inc).
I have also tried:
$blueprint_entity->field_blueprint_file->set((array)$file)
$blueprint_entity->field_blueprint_file->set(array('fid'=>$file->fid))
You need to either pass the file object or an array with a fid key to make it work.
So it's either:
// Single value field
$blueprint_entity->field_blueprint_file = array('fid' => $file->fid);
// Multi-value field
$blueprint_entity->field_blueprint_file[] = array('fid' => $file->fid);
or:
// Single value field
$blueprint_entity->field_blueprint_file = $file;
// Multi-value field
$blueprint_entity->field_blueprint_file[] = $file;
Here is complete example using value(), set() and save() from Entity metadata wrappers page:
<?php
$containing_node = node_load($nid);
$w_containing_node = entity_metadata_wrapper('node', $containing_node);
// Load the file object in any way
$file_obj = file_load($fid);
$w_containing_node->field_attachment_content->file->set( $file_obj );
// ..or pass an array with the fid
$w_containing_node->field_attachment_content->set( array('fid' => $fid) );
$w_containing_node->save();
?>
Also when dealing with multiple-valued field (cardinality > 1), make sure you wrap it into extra array.

syntax for accessing hash param in hash of hashes when using foreach

I've got this hash of hashes and I'm trying to populate a select box with values from each hash. Anyway I'm having trouble getting to my inner hash variables. I am able to generate the right number of options in my select, but I'm currently only able to set the value parameter of each select option.
Heres my hash:
my $export_types = { a => {label => "Foo", ext => ".js"},
b => {label => "Bar", ext => ".gz"}};
Heres what I've tried so far for my foreach:
my $select = "<select id='fancy'>";
foreach my $key (sort keys %{$export_types})
{
$select .= "<option value='$key' ";
if($saved_value eq $key || (!$saved_value && $key eq "a"))
{
$select .="selected='selected'";
}
$select .= ">".$export_types{$key}{label}."</option>";
}
$select .= "</select>";
apparently I'm accessing the label property wrong. For that particular line I also tried:
$select .= ">".$export_types{$key}->{label}."</option>";
but that was to no avail as well. I'm sure I'm missing something simple.
Thanks for the help :)
The expression
$export_types{$key}{label}
assumes that there is a hash %export_types. This is not the case. If you had a use strict in scope, you would have been alerted to this fact.
Because $export_types is a hash reference, we have to dereference it before using the subscript operator to access some value. Either
$export_types->{$key}{label}
or
$$export_types{$key}{label}
(I prefer the former).

Set a value to null, when calling Zend_Db::update() and insert()

My question is the exact same as How to Set a Value to NULL when using Zend_Db
However, the solution given in that question is not working for me. My code looks like the following. I call updateOper on the Model class when update is clicked on the front end. Inside updateOper, I call another function trimData() where I first trim all whitespace and then I also check that if some of the fields are coming in empty or '' I want to set them to default values or NULL values. Therefore I am using new Zend_db_expr('null') and new Zend_db_expr('default') .
The code is as follows:
private function trimData(&$data ) {
//Trim whitespace characters from incoming data.
foreach($data as $key => $val)
{
$data[$key] = trim($val);
if($data['notes'] == '') {
error_log("set notes to null/default value");
$data['notes'] = new Zend_db_expr('DEFAULT');
}
}
}
public function updateOper($data, $id)
{
$result = 0;
$tData = $this->trimData($data);
error_log("going to add data as ".print_r($data, true));
$where = $this->getAdapter()->quoteInto('id = ?', $id);
$result = $this->update($data, $where);
return $result;
}
The error_log statement prints the $data array as follows:
[id] => 10
[name] => alpha
[notes] => DEFAULT
As a result, the notes column has value ='DEFAULT' instead of picking the default value given in the table definition.
I have been trying to figure out what is wrong, but have not been able to find a solution.
I would really appreciate your help.
Thanks so much!
Your $data['notes'] is being changed to the __toString() value of the Zend_Db_Expr instead of preserving the actual object.
Maybe the reference is clogging things up. Else you may need to move the expression declaration into the actual update query.