Home / Snippets / Laravel Where Not In Condition (Eloquent)
Laravel Where Not In Condition (Eloquent) cover

Laravel Where Not In Condition (Eloquent)

285

3 years ago

0 comments

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this