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.
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.
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
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
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.
#laravel