@suhaskunte777 In the event that a Qnode does not have a Data, $item['datas'] will be empty, so no [0]. You could throw in a check to see if there's anything in $item['data'] before referencing $item['data'][0], or just get right to the point and check for the existence of $item['data'][0] itself.
Undefined offset: 0 in foreach loop
I am gettting issue in foreach loop where i am converting data into array. dd my all data is recieving but in forloop it not working. I am using Laravel 5.7
"php": "^7.1.3",
"barryvdh/laravel-debugbar": "^3.2",
"fideloper/proxy": "^4.0",
"laravel/framework": "5.7.*",
"laravel/tinker": "^1.0",
"laravelcollective/html": "^5.7",
"sven/artisan-view": "^3.1",
"way/generators": "^3.0"
hear is my code in controller '''
$node = Qnode::select('id', 'main_id')->with('datas')->get()->toArray(); foreach ($node as $item) {
//this code give me right result
dd($item['datas'][0]['pivot']['qanswer_id']);
//but here i am getting Undefined Offset:0
$data[$item['id']] = ['main_id' => $item['main_id'], 'data_id' => $item['datas'][0]['pivot']['qanswer_id']];
}
Auth::user()->qnodes()->sync($data);
'''
$item['datas']
That's an array, which may or may not always have values since it's a relationship. You're assuming it always will.
Try checking the output of this
foreach ($node as $item) {
dump($item['datas']); // does every $item contain an array of datas with values?
}
The reason why it's working with dd(), is because dd() kills the loop cycle. It's not iterating through the whole array. It iterates once until it hits the dd() and then stops. So maybe the first one has it and it outputs fine, but maybe on the 2nd iteration there is no element at position 0 in the array.
What you need to figure out is what data_id should be if $item['datas'][0]['pivot']['qanswer_id'] doesn't exist for each item.
Please or to participate in this conversation.