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

Last updated on June 9, 2023

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,

use 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 */

Check if Value Exists with contains() Method

Similarly, the collection class allows you to check if the specified value exist in the collection. To the check the value in the collection you can use contains() method that takes the value as an argument and returns boolean (true or false).

$collection->contains('Mango');
/* Output: true */

Conclusion

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


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Laravel,