Laravel contains() for multiple values

laravel, php

Solution

This should work:

$user->perms->contains(function ($val, $key) use ($subject, $action) {
    return $val->subject == $subject && $val->action == $action;
});

Problem

I want to know if it is possible to use `contains()` for multiple values. For example, let's say I have the following `perms` table: ``` TABLE `perms` ( `id` int(11) NOT NULL, `subject` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `action` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ``` Example rows: ``` INSERT INTO `perms` (`id`, `subject`, `action`) VALUES (1, 'Product', 'Create'), (2, 'Product', 'Read'), (3, 'Product', 'Update'), (4, 'Product', 'Delete'); ``` My users have a `belongsToMany` relationship with a `users_perms` table, where a user can have any number of `perms`. I want to check if a user has a perm which contains a `subject` AND an `action`. So, I want to check if a user has the perm to `Create` a `Product`. Right now the following code works when checking just the `action`: ``` $action = 'Create'; $user->perms->contains('action', $action); // true if they have ANY Create action perm ``` But I need this to also check the `subject` too, because it isn't enough to just check the `action`. So I need something like: ``` $subject = 'Product'; $action = 'Create'; $user->perms->contains([ ['subject', $subject], ['action', $action], ]); ``` How do I do this?

Original source