Laravel Tutorials

Enhance Collection Validation with containsOneItem() Closure Support

Published
Enhance Collection Validation with containsOneItem() Closure Support image

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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Load Eloquent Models From Form Request Input in Laravel image

Load Eloquent Models From Form Request Input in Laravel

Read article
Laravel FFmpeg 9: Encode Video and Stream HLS and DASH image

Laravel FFmpeg 9: Encode Video and Stream HLS and DASH

Read article
Migration Durations and Job Memory Usage in Laravel 13.45 image

Migration Durations and Job Memory Usage in Laravel 13.45

Read article
Laravel CLI: One Binary for New PHP and Rust Laravel Apps image

Laravel CLI: One Binary for New PHP and Rust Laravel Apps

Read article
Phactorial: Render LaTeX Math to SVG and PNG in PHP image

Phactorial: Render LaTeX Math to SVG and PNG in PHP

Read article
Laravel, reimagined image

Laravel, reimagined

Read article