How to use Collection Methods to check the variable in array with Laravel

Categorized as Laravel

While we have in_array function in PHP to check if a variable is present in array, we can do the same with Collections Method in Laravel.

// PHP way
if(in_array($name, ['foo', 'bar', 'haystack', 'needle'])) {
  // do something
}

// Laravel way
if(collect(['foo', 'bar', 'haystack', 'needle'])->contains($name)) {
  // do something
}

Leave a reply

Your email address will not be published. Required fields are marked *