Posts Learn Components Snippets Categories Tags Tools new About
/

Laravel Where Not In Condition (Eloquent)

Learn how to write where not in condition in Laravel the easy way

Created on Oct 26, 2021

11 views

In Laravel, you can perform a "where not in condition" to get a record that has no value for a particular column. For example, you can retrieve "posts" that the ID is not 1, 2, 3 by using the whereNotIn condition. This condition supports array values and you can write it like below.

Eloquent Model Query

<?php

Post::query()
    ->whereNotIn('id', [1, 2, 3])
    ->take(10)
    ->get();

// The query above will get the post with an id of 4, 5, 6 to 13
Do note that the whereNotIn condition is suitable for many of the values such as number, string and etc.
<?php

Post::query()
    ->whereNotIn('slug', ['hello', 'world'])
    ->take(10)
    ->get();

// The query above will get 10 posts but will exclude the one that hs 'hello' and 'world' as slug

Using DB Facade


You can also use DB facade and the way to write it is like below.
<?php

DB::table('posts')
    ->whereNotIn('id', [1, 2, 3])
    ->take(10)
    ->get();

// The query above will get the post with an id of 4, 5, 6 to 13

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)