How To Use WhereNot() In Laravel Query

Hello artisan,

In this tutorial, I will show you how to use “where not” laravel query. If you don't know how to write query with where not then this example is for you. I will share query with where not with eloquent and query builder and also. This PR by Marco van Oort now contributed two new methods, whereNot and orWhereNot, in Laravel 9.x. This allows us to build “where not” SQL claused in our queries so that you can easily build intuitive queries.

The old way we write where not condition in laravel query like:

$books = DB::table('books')
                    ->where('rating', '<=', 2)
                    ->where('author', '!=', 'Ruskin Bond')
                    ->get();

 

Now see the new way that how we can write query using where not:

$books = DB::table('books')
            ->whereNot(function ($query) {
                $query->where('rating', '>', 2)
                    ->where('author', 'Ruskin Bond')
            })
            ->get();

 

You can write the same on Eloquent models as well.

$books = Book::whereNot(function ($query) {
                $query->where('rating', '>', 2)
                    ->where('author', 'Ruskin Bond')
            })
            ->get();

 

Read also: How to Change Mail Driver Dynamically in Laravel

 

Hope it can help you.

 

#laravel #laravel-9x