Im using the code below to get all the the blueprint fields that start with the word “social” and use it to generate a list of the social media links in my sites footer. Trouble is, there is no check to see if the field has a value or not. How can i filter out the empty fields?
// Get Social Links
$socialFields = array_filter(
array_keys($site->blueprint()->fields()),
static function ($field) {
return Str::startsWith($field, 'social');
}
);
$social = [];
foreach ($socialFields as $key) {
$social[$key] = [
'label' => $site->blueprint()->field($key)['label'],
'url' => $site->{$key}()->value(),
];
}
1 Like
You could use an if statement:
foreach ($socialFields as $key) {
if ($site->{$key}()->isNotEmpty() {
$social[$key] = [
'label' => $site->blueprint()->field($key)['label'],
'url' => $site->{$key}()->value(),
];
}
}
or use an additional condition in the array_filter()
closure
Hrmm… if statement doesnt work.
Can you please explain this 
Yes, of course 
$socialFields = array_filter(
array_keys($site->blueprint()->fields()),
static function ($field) use ($site) {
return Str::startsWith($field, 'social') && $site->{$field}()->isNotEmpty();
}
);
(Well, ok, it’s not an explanation but the code example, but I think it is self-explanatory?)
Well, maybe not, so:
To pass the $site
variable to the closure, we use a use()
statement (otherwise we would get an undefined variable $site
error (the alternative would be to use the site()
helper instead of $site
).
Inside the closure, we not only check if the field starts with social, but also check if it is not empty with $site->{$field}()->isNotEmpty()
.
1 Like
Yup that did the trick
Thank you.
And actually the if statement might well have worked too, i just realised i was doing it in the wrong controller.
Yep, but it makes sense to put it in the callback where you are filtering the fields anyway. Unless you have a reason to fetch all fields first and then later filter by empty or not.