How to Check if a Key Exists in a Collection in Laravel 9

In the Laravel framework, the collection class provides a has() method that checks if a key exists in the collection. Before using the has() method make sure that you have imported the collection class into your controller. To import the collection class into your controller add the below code,

Illuminate\Support\Collection

Once it is imported you can use all methods that belong to the collection class.

Check if Key Exists with has() Method

Let’s suppose we have a fruit collection that has key values.

$collection = new Collection([
    'mango_key' => 'Mango',
    'apple_key' => 'Apple',
    'orange_key' => 'Orange'
]);

To check if the apple_key key exists in the above collection you can use has() method.

$collection->has('apple_key');
/* Output: true */

The has() method also accepts multiple keys as an argument. So if you want to check if two or more keys exist in the above collection then you need to pass the keys array into has() method as an argument.

$collection->has(['apple_key', 'orange_key']);
/* Output: true */

The has() method returns false when you pass the key that doesn’t exist.

$collection->has('wrong_key');
/* Output: false */

Similarly, if you add a key into an array that doesn’t exist in the collection then has() method will return false.

$collection->has(['apple_key', 'orange_key', 'wrong_key']);
/* Output: false */

The collection class also has a hasAny() method that checks if any key exists in the collection from the provided array. It accepts keys in an array.

$collection->hasAny(['apple_key', 'orange_key', 'wrong_key']);
/* Output: false */

Conclusion

This article teaches how to check if a key exists in the collection. If you would like to learn more about it, check out our Laravel page.