Laravel 5 Collections: Filtering a Collection Based On Key Presence With whereNotIn

April 22, 2018 —John Koster

The whereNotIn method will return all of the items in a collection that do not have matching values (supplied via the $values parameter) for the provided $key. This method is capable of filtering collections of both arrays and objects.

The whereNotIn method does not modify the original collection.

#Signature

1public function whereNotIn(
2 $key,
3 $values,
4 $strict = false
5);

#Example Use

In the following example, let's imagine we run an on-line community of users. Within this community, we have a list of users that are banned; using the whereNotIn method, we can easily get all of our users that are not banned:

1// A record of banned users.
2$bannedUsers = [
3 'Charlie',
4];
5 
6// A collection of all users.
7$users = collect([
8 ['username' => 'Alice'],
9 ['username' => 'Bob'],
10 ['username' => 'Charlie'],
11]);
12 
13// Get all users that are not banned.
14$notBannedUsers = $users
15 ->whereNotIn('username', $bannedUsers);

By default, the whereNotIn method does not perform strict comparisons when building up the final results collection. Lets refactor our previous example to have a flag set on each user indicating whether they are banned, rather than having a separate list of banned users:

1$users = collect([
2 [
3 'username' => 'Alice',
4 'isBanned' => true
5 ],
6 [
7 'username' => 'Bob',
8 'isBanned' => 'true'
9 ],
10 [
11 'username' => 'Charlie',
12 'isBanned' => 1
13 ]
14]);

Now, we will use the whereNotIn method with strict comparisons enabled (by supplying a truthy argument for the $strict parameter):

1$notBannedUsers = $users
2 ->whereNotIn('isBanned', [
3 true // Get all unbanned users.
4 ], true); // Enable strict comparisons.

After the above code has executed, we would receive a collection of users that contains both Bob and Charlie. This is because the record for Alice is the only record where the value of isBanned matches the type we specified when invoking the whereNotIn method with strict comparisons enabled.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.