How can I clean up this data set in a controller?

This is not strictly a Roots question but my guess is another Roots dev has had to deal with something similar. I’m working on a theme that will display categories applied to a post in several places, so I want to set up a static function in my controller. I don’t want to use the native WP markup, and I don’t want to display any ‘uncategorized’ posts so I’m attempting to use Laravel collection methods to map the WP data.

$categories = collect(get_the_category())->map(function ($category){
  if( $category->slug !== 'uncategorized' ) {
    $lpeCategory = (object) [
     'name' => $category->name,
     'link' => home_url('/') . $category->taxonomy . '/' . $category->slug
    ];
    return $lpeCategory;
  }
})->filter();

The issue is, if I apply this map function to a post that belongs to “uncategorized” and nothing else, Laravel still returns a collection object that contains an empty array, so I can’t test @if($categories) in my Blade template. I tried using the Laravel filter, flatten, etc. methods but they don’t consider the empty object to be falsey. This was the best workaround I could think of to get usable data to the Blade template:

if (!empty($categories->all()[0])) {
  return $categories;
} else {
  return false;
}

Surely there’s something obvious I’m missing—how can I test for / remove an empty collection?

https://laravel.com/docs/7.x/collections#method-isempty perhaps?

1 Like

I should have mentioned I did try isEmtpy() too—Laravel doesn’t consider a blank collection to be empty. It still contains an array with a NULL entry. count(blankCollection) comes back at as 1, too.

https://implode.io/rnff94

1 Like

Use ->filter() to filter, and you’ll end up with an actually empty collection, not a collection with one empty item:

$categories = collect(get_the_category())
  ->filter(function ($category) {
    return $category->slug !== 'uncategorized';
  })
  ->map(function ($category) {
    return (object) [
     'name' => $category->name,
     'link' => home_url('/') . $category->taxonomy . '/' . $category->slug
    ]; 
  });

return $categories->isEmpty() ? $categories : false;
2 Likes

That’s brilliant, thanks! Definitely does the trick, appreciate the guidance!

Thanks, this is super helpful. I have never seen implode before, it’s a great resource! I am struggling to recreate the exact isEmpty scenario I ran into last night but it’s good to have a nice web ide for laravel!

This topic was automatically closed after 42 days. New replies are no longer allowed.