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

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 = false5);
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 = $users15 ->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' => 113 ]14]);
Now, we will use the whereNotIn
method with strict comparisons enabled (by supplying a truthy argument for the $strict
parameter):
1$notBannedUsers = $users2 ->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.
∎
Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.
Sponsor on GitHub Shop Merch