Hello Artisan
In this tutorial i will show you how we can use contains collection method in laravel. The contains()
method determines whether the collection contains a given item. If contains then it returns true otherwise false.
The contains()
method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. So let's see how to check an array items using contains.
Example 1 : contains()
See the first example of laravel contains method
Route::get('/', function () {
return collect(['hello'])->contains('hello');
});
If we run this code the output will be true cause the collection contains hello.
Route::get('/', function () {
return collect(['hello'])->contains('hi');
});
If we run this code then the output will be false. Cause contains
method doesn't determines the collection contains that given item.
Example 2 : contains()
Route::get('/', function () {
return collect(['key' => 'value'])->contains('value');
});
If we run this code the output will be true cause the collection contains value. So we can pass key also in collection arrays.
Example 3 : contains()
We can slo check by the following manner
Route::get('/', function () {
return collect([
['key' => 'value']
])->contains('key','value');
});
Example 4 : contains()
Check a little bit more advance example. Have a look
Route::get('/', function () {
return collect([1,2,3,4])->contains(function($value,$key){
return $value > 3;
});
});
Here $value is checking from collection that whether 1 is greater than 3 or not, 2 is greater than 3 or not, 3 is greater than 3 or not, 4 is greater than 3 or not, If greater then the whole item will return true. If the one condition is true there will be whole item true. Hope it can help you.
#laravel #laravel-collection #collection