Reputation: 567
I am basically trying to achieve the following layout in a Laravel blade:
17th
25th
1st
13th
16th
How do I get to this from having an array of dates, for example:
array (size=5)
'id' => int 1
'tour_id' => int 1
'start_date' => string '2014-10-17 00:00:00' (length=19)
'end_date' => string '2014-10-24 00:00:00' (length=19)
'price' => int 12503
array (size=5)
'id' => int 2
'tour_id' => int 1
'start_date' => string '2014-10-25 00:00:00' (length=19)
'end_date' => string '2014-10-31 00:00:00' (length=19)
'price' => int 12503
array (size=5)
'id' => int 3
'tour_id' => int 2
'start_date' => string '2014-11-01 00:00:00' (length=19)
'end_date' => string '2014-11-11 00:00:00' (length=19)
'price' => int 12503
array (size=5)
'id' => int 4
'tour_id' => int 3
'start_date' => string '2014-11-13 00:00:00' (length=19)
'end_date' => string '2014-11-31 00:00:00' (length=19)
'price' => int 12503
array (size=5)
'id' => int 5
'tour_id' => int 3
'start_date' => string '2014-12-16 00:00:00' (length=19)
'end_date' => string '2014-12-31 00:00:00' (length=19)
'price' => int 12503
I am returning this array to the view from my controller with the following line:
'tourDates' => $this->tourDate->all(['tour'], ['column' => 'start_date', 'order' => 'asc'])
Upvotes: 2
Views: 2688
Reputation: 111829
You can use something like this:
$data = [
[
'id' => 1,
'start_date' => '2014-10-17 00:00:00',
],
[
'id' => 2,
'start_date' => '2014-10-25 00:00:00',
],
[
'id' => 3,
'start_date' => '2014-11-01 00:00:00',
],
[
'id' => 4,
'start_date' => '2014-11-13 00:00:00',
],
[
'id' => 5,
'start_date' => '2014-12-16 00:00:00',
]
];
$month = '';
use Carbon\Carbon;
foreach ($data as $item) {
$date = new Carbon($item['start_date']);
if ($date->format("F") != $month) {
$month = $date->format("F");
echo '<h1>'.$month.'</h1>';
}
echo $item['id']."<br />";
}
Of course it's PHP code, you can first save this data and then assign it to Blade or template in other format.
You could do it this way for Blade:
$data = [
[
'id' => 1,
'start_date' => '2014-10-17 00:00:00',
],
[
'id' => 2,
'start_date' => '2014-10-25 00:00:00',
],
[
'id' => 3,
'start_date' => '2014-11-01 00:00:00',
],
[
'id' => 4,
'start_date' => '2014-11-13 00:00:00',
],
[
'id' => 5,
'start_date' => '2014-12-16 00:00:00',
]
];
$months = '';
foreach ($data as $item) {
$date = new Carbon($item['start_date']);
$months[$date->format("F")][] = $item;
}
return View::make('dates')->with('months',$months);
And in Blade:
@foreach ($months as $month => $items)
<h1>{{{ $month }}}</h1>
@foreach ($items as $item)
{{{ $item['id'] }}}<br />
@endforeach
@endforeach
Upvotes: 3