How can I check value of Collection in one line?
For example: auth()->user()->roles->findKeyWithValue('title' => 'Admin')
I need for Middleware, like: if (auth()->user()->roles->existInCollection(['title' => 'Admin'])
CodePudding user response:
You can check if the role exists using contains
:
if (auth()->user()->roles->contains('title', 'Admin')) {
// true
}
Doc: https://laravel.com/docs/9.x/collections#method-contains
CodePudding user response:
You don't need to retrieve a collection if all you're doing is checking for existence of a single record.
if (auth()->user()->roles()->where("title", "admin")->exists()) {
...
}
This will query the database only for whether or not the given record exists. What you are attempting to do with a collection is fetching all the fields of every entry from the database, and then doing a foreach
loop to check every item and see if it matches.
For something as small as a list of user roles, going through that process won't be very hard on your response times and server resources. But it's good practice to avoid retrieving needless datasets when possible.