I’m trying to determine if a String is included in a array of strings in Laravel.
I have
$rol = 'Admin';
$roles = ['Admin', 'Guest'];
I want to know if $rol is included in $roles without looping.
In Javascript it would be something like this
let array = ['Admin', 'Guest']
let role = 'Admin'
array.includes(role)
If I do this in Laravel, there are some cases I’m not expecting:
Str::contains($rol, $roles) //Output would be true
But if now $roles = ['dmin', 'Guest']
instead of ['Admin', 'Guest']
Str::contains($rol, $roles) //Output would be true but I'm expecting false as 'Admin' is not a $roles element
4
Answers
You should not use
Str::contains
which checks if the string contains (e.g. has a substring) any of the provided values, but Collection contains, e.g.collect($roles)->contains($rol)
.in_array
function from php.For example:
You can also convert the array to the type
collection
which is brought to your by Laravel framework. Just simply pass the array to the functioncollect()
. For example:After that apply any conditions which are applicable to the collection type.
Laravel has a lot of
helper
methods. The one you’re likey after is theArr::has
method:This method is particularly handy when working with nested arrays. Using dot notation you can perform the same lookup without having to write that logic yourself.
Try this one, it’s not Laravel but PHP.
use stripos function.