Use containsOneItem() on Laravel Collections instead of count() === 1 to write cleaner, more expressive dataset assertions.
Checking whether a collection or filtered list contains exactly a single item (such as checking if a user has only one registered payment method or verifying single-item cart status) traditionally required $collection->count() === 1.
Laravel provides the expressive containsOneItem() method.
Basic Usage
$cart = collect([
['id' => 1, 'name' => 'Book', 'price' => 20]
]);
// Clear and readable
if ($cart->containsOneItem()) {
$item = $cart->first();
// Apply single-item shipping rate
}
In Authorization or Business Logic
// Prevent deleting the only remaining administrator account
if ($team->admins->containsOneItem()) {
abort(422, 'Cannot remove the last remaining administrator.');
}
Summary
- Returns
trueonly if the collection contains exactly 1 item; returnsfalseif empty or containing multiple items. - More expressive than checking count equality.
- Available on all Laravel
CollectionandLazyCollectioninstances.
Related Tips
View all tips →Simplify Collection Operations with Higher-Order Messages
Laravel Collections support higher-order messages through dynamic properties, allowing operations like each, map, filter, and groupBy to work directly with an item's property or method without writing boilerplate callbacks.
Generate Iterative Collections Quickly with Collection::times()
Use Collection::times() to generate numeric-sequence collections or execute closures N times fluently without writing for loops.