Enhanced Collection Validation with containsOneItem() Closures

Laravel enhances the containsOneItem() method with closure support, allowing you to verify that exactly one item satisfies custom conditions.
Previously, containsOneItem() could only check if a collection had exactly one item total. The enhanced method now accepts closures, enabling you to verify that exactly one item meets specific criteria, making your collection validations more precise.
Let's see how it works:
$collection = collect([1, 2, 3]);
$collection->containsOneItem(fn($item) => $item === 2); // true
$collection->containsOneItem(fn($item) => $item > 1); // false (2 and 3 match)
Real-World Example
Here's how you might use this in a validation service:
class ValidationService
{
public function validateUserRoles(Collection $users)
{
// Ensure exactly one admin exists
if (!$users->containsOneItem(fn($user) => $user->role === 'admin')) {
throw new ValidationException('Exactly one admin required');
}
// Ensure exactly one primary contact
if (!$users->containsOneItem(fn($user) => $user->is_primary_contact)) {
throw new ValidationException('Exactly one primary contact required');
}
return true;
}
public function validateOrderItems(Collection $items)
{
$validations = [
'shipping' => $items->containsOneItem(fn($item) => $item->type === 'shipping'),
'discount' => $items->containsOneItem(fn($item) => $item->type === 'discount'),
'tax' => $items->containsOneItem(fn($item) => $item->type === 'tax')
];
foreach ($validations as $type => $isValid) {
if (!$isValid) {
throw new ValidationException("Exactly one {$type} item required");
}
}
return $items;
}
}
This enhancement provides precise control over collection validation, ensuring that exactly one item meets your specific conditions rather than just checking collection size.
Stay Updated with More Laravel Tips
Enjoyed this article? There's plenty more where that came from! Subscribe to our channels to stay updated with the latest Laravel tips, tricks, and best practices:
- Follow us on Twitter @harrisrafto
- Join us on Bluesky @harrisrafto.eu
- Subscribe to our YouTube channel harrisrafto