Ensure type uniformity of a collection in Laravel
Sometimes, you may want to ensure that a collection in Laravel contains only a specific type of item. For instance, you may want to ensure that a collection contains only a string
type of item. Or, you may want to ensure that a collection contains items of a specific class.
Laravel provides a convenient way to do this using the ensure
method on the Collection
class. This method accepts the type of items you want to ensure in the collection as its first argument and the collection itself as the second argument.
$collection = collect(['John', 'Jane', 'Doe']);
$hasOnlyStrings = $collection->ensure('string');
// true
Here, the $hasOnlyStrings
variable will be true
because the $collection
contains only string
type of items.
Similarly, you can ensure that a collection contains only items of a specific class like so.
class Person
{
public string $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
$collection = collect([
new Person('John'),
new Person('Jane'),
new Person('Doe'),
]);
$hasOnlyPersons = $collection->ensure(Person::class);
But if you pass a collection that contains items of different types, the ensure
method will throw an UnexpectedValueException
exception.
$collection = collect(['John', 'Jane', 1]);
$hasOnlyStrings = $collection->ensure('string');
// UnexpectedValueException: The collection must
// contain only string values.
All in all, this is a pretty handy method to ensure the type uniformity of a collection in Laravel.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.