Get all unique years from a date field

Struggling to get my head around this one, hoping someone can help.

I have a page called timeline it has many children that are timeline events and each has a date field.

In my controller what I am trying to do is this:

Get the date (event_date) from all of the children.
Extract the year from each date but return only the unique years.
But, a further twist is that I only want years between 1933-1945.
Then I can return that array of years to the page and loop through to display.

What would be your approach to this?

Thanks very much for any comments. For reference, if it helps to understand, see a screenshot of my local test site with Laravel where I did it. Relates only to that top row of years you can see. Just can’t figure out how to duplicate with Kirby.

You can first filter the timeline subpages by date from - to, see: Filtering compendium | Kirby CMS

$events = page('timeline')
  ->filterBy('date', 'date >', '1933-01-01')
  ->filterBy('date', 'date <', '1945-12-31');

Then use map() to return a field with the date formatted as year:

$events = $events->map(function($event) {
      $event->year = $event->date()->toDate('Y');
      return $event;

Then use pluck() to get a array of uniques years from the filtered pages collection: $pages->pluck() | Kirby CMS

$years = $events->pluck('year', ',', true);
1 Like

You’re too quick as always :slight_smile:

Thank you, I am overthinking it as always and of course the way Laravel uses map should never be assumed to be the way other software or just simple PHP uses it!