1

I have an $events object that gets a bunch of results from various tables in my database using Query Builder in Laravel 4. See here http://paste.laravel.com/qIj

I'd like to separate those results in to week commencing, so when I output them in my view it groups everything by week, based upon the information in the start_date field of the events table.

Any ideas how best to achieve this? Cheers.

Gareth Daine
  • 4,016
  • 5
  • 40
  • 67

2 Answers2

4

I usually do something like this:

<?php
// Event model
public function getAllByWeek() {
    $events = static::orderBy('created_at', 'DESC')->get();
    $orderedEvents = array();

    foreach ($events as $event) {
        $date = new \DateTime($event->created_at);
        $weekCategory = $date->format('oW');
        $weekFormatted = $date->format('W');

        if ( ! array_key_exists($weekCategory, $orderedEvents)) {
            $orderedEvents[$weekCategory] = (object) array(
                'week' => $weekFormatted,
                'events' => array(),
            );
        }

        $orderedEvents[$weekCategory]->events[] = $event;
    }

    return $orderedEvents;
}

// Controller
$orderedEvents = Event::getAllByWeek();

// View
@foreach ($orderedEvents as $eventsHolder)

    {{ $eventsHolder->week }}

    @foreach ($eventsHolder->events as $event)

        // content output

    @endforeach

@endforeach
Nicholas Ruunu
  • 603
  • 5
  • 12
0

Does this help? I am not familiar with query builder but can you pass the week commencing to it?

Get date of Monday in current week in PHP 4

Community
  • 1
  • 1
lukeocodes
  • 1,192
  • 1
  • 16
  • 31