Laravel 5

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


John Koster

Published on April 22, 2018

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.


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

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',
6// A collection of all users.
7$users = collect([
8 ['username' => 'Alice'],
9 ['username' => 'Bob'],
10 ['username' => 'Charlie'],
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 ]

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.

Explore The Blog

Laravel String Pluralization

Published on November 30, 2016

Read More

Laravel String Helper Function: str_plural

Published on November 16, 2016

Read More