Reputation: 1983
I am using Laravel as my framework but it is not a laravel question, per se. From an array, I am trying to display results for each month, as follows:
<table>
<tr>
<td>January</td>
</tr>
<tr>
<td>First result for january</td>
<td>Second result for january</td>
</tr>
<tr>
<td>February</td>
</tr>
<tr>
<td>First result for february</td>
<td>Second result for february</td>
</tr>
</table>
In my controller I am getting the results as follows:
$results = Expense::whereBetween('date', array($start, $end))->get();
Where $start
and $end
are dates that I gather from my input, in the format YYYY-MM-DD
.
In my view I display the results like this (example):
@foreach($results as $result)
{!! $result->date !!} - {!! $result->expense !!} - {!! $result->amount !!}
@endforeach
But I would like to have it like in the above example. So, when in my input I select different months, also the view changes, so I cannot hard code it in. I basically need to change my foreach to display a month, with all results from that month below that, and then display the next month, and so on.
A nudge in the right direction would be helpful.
Upvotes: 1
Views: 68
Reputation: 29231
I would group the results using Laravel Collections methods:
$results = Expense::whereBetween('date', array($start, $end))->get();
$results = $results->groupBy(function($expense)
{
return Carbon\Carbon::parse($expense->date)->month;
});
Then you will have your results in the following format:
=> Illuminate\Database\Eloquent\Collection {#2708
all: [
1 => Illuminate\Database\Eloquent\Collection {#1427
all: [
App\Expense {#1410 …27},
App\Expense {#3077 …27},
App\Expense {#1408 …27},
...
],
},
2 => Illuminate\Database\Eloquent\Collection {#1428
all: [
App\Expense {#1310 …27},
App\Expense {#3377 …27},
App\Expense {#1308 …27},
...
],
},
3 => Illuminate\Database\Eloquent\Collection {#1429
all: [
App\Expense {#1810 …27},
App\Expense {#3877 …27},
App\Expense {#1808 …27},
...
],
},
...
],
}
Each key will represent a month number.
Upvotes: 2