Collection::sole()
Get exactly one matching item from a collection — or throw an exception. A stricter alternative to first().
Overview
sole() returns the only element in a collection that matches a given truth test. If zero or more than one element matches, it throws an exception. It enforces a "there must be exactly one" invariant.
Usage
collect([1, 2, 3, 4])->sole(fn ($value) => $value === 3);
// 3
If no items match:
collect([1, 2, 3])->sole(fn ($value) => $value === 5);
// throws ItemNotFoundException
If multiple items match:
collect([1, 2, 2, 3])->sole(fn ($value) => $value === 2);
// throws MultipleItemsFoundException
It also works on Eloquent queries:
// Throws if not exactly one active admin
User::where('role', 'admin')
->where('is_active', true)
->sole();
When to Use
- Enforcing uniqueness constraints in business logic
- Fetching a record where exactly one result is expected (API keys, config rows)
- Replacing
first()when having 0 or 2+ results would be a bug