Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top