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?