Filter a Grouped Collection by Tags

Hey all,

I’m stuck on something. I’ve made a collection, grouped by year, and have that working on my blog archive page. However, I want to filter that collection by tags, so those can be viewed. I’m unsure how to drill down into the collection to get at the posts and filter them properly in the controller. I’ve experimented with a foreach loop, but wasn’t sure if that was the best approach.

Here’s my current code.

blogbyyear.php collection:

<?php

return function() {
  $byYear = function($p) {
    return $p->date()->toDate('Y');
  };
  return page("blog")
    ->children()
    ->listed()
    ->sortBy("date", "desc")
    ->paginate(10)
    ->group($byYear);
};

blog.php controller:

<?php

return function ($page) {
  $blogbyyear = collection("blogbyyear");

  // Doesn't work, returns empty object.
  if ($tag = param('tag')) {
    $blogbyyear = $blogbyyear->filterBy('tags', $tag, ',');
  }

  return [
    "tag"   => $tag,
    "blogbyyear" => $blogbyyear
  ];
};

Appreciate any insight you all have.

It would make more sense if your collection was not sorted, paginated or grouped, because applying a filter afterwards doesn’t make sense.

So from your collection, only return a simple collection:

  return page("blog")
    ->children()
    ->listed();

Then do the rest in your controller. Filter first, then sort, then group.

1 Like

Ah, so much simpler! Thank you, Sonja for the helpful and speedy reply.