• Reading time ~ 1 min
  • 05.06.2025

Laravel improves collection validation by adding closure support to the containsOneItem() method, enabling developers to verify that exactly one item satisfies custom conditions rather than just checking collection size.

Previously, containsOneItem() could only determine if a collection contained exactly one item total. The enhanced method now accepts closures, allowing precise validation that exactly one item meets specific criteria:

$collection = collect([1, 2, 3]);
$collection->containsOneItem(fn($item) => $item === 2); // true
$collection->containsOneItem(fn($item) => $item > 1);   // false (2 and 3 match)

This enhancement proves particularly valuable in business rule validation scenarios:

class BusinessRuleValidator
{
    public function validateTeamStructure(Collection $members)
    {
        // Ensure exactly one team lead exists
        if (!$members->containsOneItem(fn($member) => $member->role === 'lead')) {
            throw new ValidationException('Exactly one team lead required');
        }
        // Ensure exactly one budget approver
        if (!$members->containsOneItem(fn($member) => $member->can_approve_budget)) {
            throw new ValidationException('Exactly one budget approver required');
        }
        return true;
    }
    public function validateInvoiceItems(Collection $items)
    {
        $validations = [
            'handling' => $items->containsOneItem(fn($item) => $item->type === 'handling'),
            'processing' => $items->containsOneItem(fn($item) => $item->type === 'processing'),
            'delivery' => $items->containsOneItem(fn($item) => $item->type === 'delivery')
        ];
        foreach ($validations as $type => $isValid) {
            if (!$isValid) {
                throw new ValidationException("Exactly one {$type} fee required");
            }
        }
        return $items;
    }
}

The enhanced containsOneItem() method provides precise collection validation by ensuring exactly one item meets specific conditions, making business rule enforcement more reliable and expressive.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297

We shoot down "Shahed" drones every day. Each one downed means lives saved. But we need mobility: a van or a trailer. Every donation = another night under protection.

🚐 Van fundraiser for my unit, 1020 regiment 🎯 Goal: 500,000 ₴
🔗 Donation link 💳 4441 1111 2546 4663