I have an multidimensional array that I pass to a view in laravel. This array is used to output data to the view using blade syntax. But when I try to access a key in a @foreach loop I receive an error Invalid argument supplied for foreach() .
When I output the same array index within php tags the line before the @foreach () loop, there is no error.
Can someone please give me a clue to why this would happen?
array var_dumped : $item['all']
@php
echo var_dump($item['all']);
die();
@endphp
array (size=1)
0 =>
array (size=22)
'withdraw_prod' => int 0
'class_id' => int 10
'optional' => int 0
'extra' => int 0
'stage' => string 'NA' (length=2)
'pest' => string 'NA' (length=2)
'product' => string 'Monitering' (length=10)
'description' => null
'active' => null
'class' => string 'Ander' (length=5)
'rac_code' => null
'htwoo' => string '0' (length=1)
'prod_ha' => string '2.98' (length=4)
'kgl_ha' => string '0.0000' (length=6)
'hundred_met' => null
'total' => string '0.0000' (length=6)
'cost_kgl' => null
'cost_total' => null
'heading' => null
'header' => int 0
'hex' => null
'is_na' => boolean true
Code next line that gives error:
@foreach ($item['all'] as $k => $spray)
Some LOG output:
<?php $__currentLoopData = $item['all']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $k => $spray): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
Laravel 5.6.39
Edit: I am trying to output data to a view that is generating a pdf from controller:
$pdf = PDF::loadView('direct.tory.here.is.pdf', compact('program', 'taboo', 'colour', 'footnotes'))->setPaper('a4', 'landscape');
The loops in the view is:
@foreach ($program as $key => $item)
@if(!in_array($key, $taboo))
@php
$cnt = 0;
$extra_row = 0;
//echo var_dump($item['all']);
@endphp
@foreach ($item['all'] as $k => $spray)
@php
// for in case array dimensions differ
$sprays = (array_key_exists(0, $spray)) ? $spray[0] : $spray;
if(!empty($sprays['description'])) {
$extra_row++;
}
@endphp
@endforeach
@endif
@php
$col++;
@endphp
@endforeach
Solved it
This is a bit embarrassing, but I had created an array with taboo keys that filtered out non array values from my main array $program. For testing two months ago an extra dummy key => value that contained an integer was added for testing, but was never added to the taboo list. This dummy integer value was slipping through causing the @foreach loop not being able to iterate over the $item['all'] which did not exist for that array index.
Thank you for your input all who commented.
I had created an array with taboo keys that filtered out non array values from my main array
$program. For testing two months ago an extra dummykey => valuethat contained an integer was added for testing, but was never added to the taboo list. This dummy integer value was slipping through causing the@foreachloop not being able to iterate over the$item['all']which did not exist for that array index.So solution is oversight and not
type checkingbefore using a value.