Filter to sort post with same category


Wanted to check if there is any easier way of doing this,
I’m pulling the posts that have the same category and listing them in a groups of A, B, C.

<?php $A = $page->children()->filter(function($child) {
  return str::startsWith($child->cat(), 'A');
}); ?>

<?php $B = $page->children()->filter(function($child) {
  return str::startsWith($child->cat(), 'B');
}); ?>

<?php $C = $page->children()->filter(function($child) {
  return str::startsWith($child->cat(), 'C');
}); ?>

This all work great! Just curious if i would add a new category “D” in the future is there away to do this in a more automatically solution and the one above.

Thankful for guidance <3

I don’t quite understand what you are trying to achieve, why are you looking to group categories that start with a particular letter? In your first sentence you are asking for “the same category”?


I’m trying to achieve a list for a menu that takes each category that start with the same letter and group them something like this:

  • Menu

A Project-1
A Project-3
A Project-5

B Project-2
B Project-4
B Project-6
B Project-8

C Project-7

if I would add another category in the future i would have to add a separate function for the letter “D” and so on and was wondering if there is anyway to automatically do this? I guess to not specify each letter and just see if the name is the same and group those together.


Grouping them by category name is quite simple, you can use the pluck() function to get all categories and then filter by those categories, if you do this within a foreach loop, you can create these filter groups automatically.

As for grouping by letter, you could use the pluck() function first to get all unique categories, then get an array of all first letters from the categories array, and then use a loop to create these filter groups.

@texnixe pluck function looks exactly what I’m looking for. thanks for all the help!