Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?