Published on April 22, 2018
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.
whereNotIn method does not modify the original collection.
1public function whereNotIn(2 $key,3 $values,4 $strict = false5);
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];56// A collection of all users.7$users = collect([8 ['username' => 'Alice'],9 ['username' => 'Bob'],10 ['username' => 'Charlie'],11]);1213// 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' => true5 ],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
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.
Learning text parsing, manipulation, encoding and more through the Laravel string helpers.
Published on November 30, 2016
Published on November 16, 2016
Published on April 14, 2018