I am new to Laravel and coding. Trying to show Month name (Array) in table but not able to do the same. I tried few things like "json_encode" but got error each time.
My controller code is
$months = array();
for ($i = 0; $i < 12; $i ) {
$timestamp = mktime(0, 0, 0, date('n') - $i, 1);
$months[date('n', $timestamp)] = date('M-Y', $timestamp);
}
Output is
array:12 [▼
3 => "Mar-2022"
2 => "Feb-2022"
1 => "Jan-2022"
12 => "Dec-2021"
11 => "Nov-2021"
10 => "Oct-2021"
9 => "Sep-2021"
8 => "Aug-2021"
7 => "Jul-2021"
6 => "Jun-2021"
5 => "May-2021"
4 => "Apr-2021"
]
View file
<table id="incometable" data-order='[[ 0, "desc" ]]'>
<thead>
<tr>
<th align="center">Month</th>
<th>Milk Sale Amount (Rs.)</th>
<th>Animal Sale Amount (Rs.)</th>
<th>Other Sale Amount (Rs.)</th>
</tr>
</thead>
<tbody>
@foreach ($months as $item )
<tr>
<td>{{ $item->$months }}</td>
</tr>
@endforeach
</tbody>
</table>
Thanks in Advance
CodePudding user response:
During your @foreach()
loop, $item
is not an Object, it is a String 'Mar-2022'
through 'Apr-2021'
. You need to adjust your code:
@foreach($months as $key => $label)
<tr>
<td>{{ $label }}</td>
<tr>
@endforeach
If you need the 1
through 12
values, they are available in each iteration as $key
.