First of all, thanks for fixing the groupBy
method on the $pages
collection with 2.2 @bastianallgeier
I currently have a field only storing the year
, so grouping with $page->children()->groupBy('year')
works perfectly fine. However I would like to update the blueprint to store a date instead. Obviously I will remove the year field then.
Unfortunately that means that I canāt group by year anymore. A solution might be to let groupBy
accept a callback like so:
$page->children()->groupBy(function ($child) {
return $child->date('Y');
});
Said function would have to return the āgroupā its argument page belongs to. I think this would be very powerful - you could group by number of subpages, number of images, ⦠(even though I have a hard time coming up with a use case for that). There are some drawbacks or possible pitfalls though. Most importantly the developer has to be cautious to only return values that can be used as array keys later.
I would happily send a pull request for that but wanted to hear everybodyās opinion first. What do you think? Is this simple/intuitive enough to use? Is being able to group by year from a date field worth a few extra lines of code in the core? Or should this be handled in the template/model/controller with loops, pluck
, ⦠like in the dark times before 2.2?
EDIT: I just came up with another use case: my users have a field info
possibly storing stuff like ābossā, āour best developerā and so on. Additionally, I have a template with a list of all users with a given role. There, people with a specified āinfoā should be listed before those without as they are usually searched for more often. Right now my code is quite messy:
<?php foreach (array('!=', '==') as $comp): ?>
<?php foreach($site->users()->filterBy('funktion', $comp, '')->sortBy('firstName', 'ASC') as $person): ?>
<li><?= $person->firstName()</li> // Waaay more complicated in real code
<?php endforeach; ?>
<?php endforeach; ?>
So, first I filter out all people that have information, show their profiles, and then do the exact same thing with those without information. This works, but doesnāt look nice.
<?php foreach ($site->users()->groupBy(function($user) {
return ($user->info() == "") ? "noInfo" : "info"
}) as $group: ?>
<?php foreach ($group as $person): ?>
<li><?= $person->firstName()</li> // Waaay more complicated in real code
<?php endforeach; ?>
<?php endforeach; ?>
Something like that could be an alternative.