Laravel: Understanding Collections’ Higher Order Messages

Get off my lawn, you dirty closure!

$users = collect([
1 => [
'name' => 'John',
'age' => 31
'is_admin' => false,
],
2 => [
'name' => 'Mike',
'age' => 16
'is_admin' => true,
],
3 => [
'name' => 'Carmen',
'age' => 58
'is_admin' => false,
],
4 => [
'name' => 'Abby',
'age' => 24
'is_admin' => true,
],
]);
$admins = $users->filter(function (array $user) {
return $user['is_admin'];
});
$admins = $users->filter->is_admin;

What about sum, for example?

$admins = $users->sum(function (array $user) {
return $user['is_admin'] ? 1 : 0;
});
// 2
$admins = $users->sum->is_admin; // 2

Can you use methods? With arguments?

class User extends Model
{
public function ageAbove(int $age)
{
return $this->age > $age;
}
}
$users = User::all();$adults = $users->filter(function (User $user) {
return $user->ageAbove(21);
});
$adults = $users->filter(function (User $user) use ($age) {
return $user->ageAbove($age);
});
$adults = $users->filter->ageAbove(21);

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store