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')
  ->children()
  ->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!

How could I update this to not use a dynamic property ($event->year)?

Creation of dynamic property Kirby\Cms\Page::$year is deprecated

Create a page model method/custom page method that returns the year, then pluck that

	
	public function year()
	{
		return parent::date()->toDate('Y');
	}
dump($page->children()->pluck('year', ',', true));

Not sure what I’m doing wrong here…

site/models/journal.php

<?php

class JournalPage extends Page {
	public function year()
	{
		return parent::date()->toDate('Y');
	}
}

$page->children()->pluck('year', ',', true); is returning an empty array

What is the JournalPage?

And what does $page refer to in $page->children()->pluck('year', ',', true);

Or to ask the question differently: Which blueprint do the children use?

And is your field in the children called date?

True, the children use two different blueprints. I switched it to DefaultPage, not sure if that’s the best way to do it though, but this works:

<?php

class DefaultPage extends Page {
	public function year()
	{
		return $this->date()->toDate('Y');
	}
}