Laravel contains() & containsStrict(): Check if Laravel Collection contains Value

By Parth Patel on Oct 05, 2020

Today, we will review Laravel contains() method and Laravel containsStrict() method which is used to determine whether the collection contains a given value or not. This method applies to both Laravel Collection as well as Eloquent Collection object.

Laravel contains() Method

contains() method checks whether Laravel Collections contains certain given value or not. If you pass one value to the contains() method, it will check whether collection has any value matching to the parameter.

Another option is - You can also pass key / value parameter ~ first parameter is key and second parameter is value and it will match for the pair exclusively.

Check if Laravel Collection contains value

Let's review an example with one parameter (checking only value):

$users = collect(['name' => 'John Doe', 'email' => 'johndoe@example.com']);

$users->contains('John Doe');

// true

$users->contains('John Admin');

// false

Check if Laravel Collection contains key/value pair

Let's review an example with two parameters (checking whether collection contains key / value pair):

$collection = collect([
			['id' => '200', 'amount' => '500'],
			['name' => '201', 'country' => '200'],
		]);

$collection->contains('amount', '500');
//true

$collection->contains('id','500');
//false

Also Read: Laravel Pluck() Method with Example

Check if Laravel Collection contains value using callback function

Lastly, you can also pass callback function with your own matching expression to check whether laravel collection or eloquent collection contains given value or not.

Let's try an example with eloquent collection this time:

$products = Product::all();
//
Illuminate\Database\Eloquent\Collection {#4618
     all: [
				App\Product {#123
					id: 1,
					name: "Macbook",
					product_count: 2
				},
				App\Product {#123
					id: 1,
					name: "iPhone",
					product_count: 20
				},
			],
		}

//Let's check if any product has count less than 5

$products->contains(function($product, $key) {
			return $product->product_count < 5; 
			});
//True

$products->contains(function($product, $key) {
			return $product->product_count < 1;
			});
//False

Laravel containsStrict() Method

Laravel Collection's containsStrict() method function same as contains() method except it checks for value using strict comparison i.e matches value type as well

If you don't know about strict comparison, in PHP === and !== are strict comparison operators and it compares both value and type. Example: 20 and "20" are not equal in strict comparison but are same in regular comparison.

Example:

$collection = collect(["10","11","12"]);

$collection->containsStrict("10"); //true

$collection->containsStrict(10); //false

In conclusion, contains() is very simple and helpful laravel method for your collection. Try it and let me know how that works out for you!