DEV Community

Cover image for Laravel 9 WhereNotIn Database Query Examples
Suresh Ramani
Suresh Ramani

Posted on • Originally published at techvblogs.com

Laravel 9 WhereNotIn Database Query Examples

Laravel framework has been in demand for some time now. Its expressive command line structure has mesmerized the coding world. The framework is also known for its robust scalability. Laravel is one of the most sought-after of frameworks for eCommerce solutions because of the sheer number of options it provides. One can use its vast library to create functionalities that will help the users. The best feature of Laravel is probably is its ability to provide the developer with myriad options for the same query. This makes the job of the developer that much simpler. Expressive queries lead to greater flexibility and a better understanding of the need of the user and the functionality.

This tutorial provides you simple examples of where Not In Laravel Query Builder. And as well as how to use Laravel Eloquent WhereNotIn with arrays.

Laravel Eloquent "WHERE NOT IN" Query Examples

The wherenotin() database query method takes two parameters. In the first argument, you pass the column name, and the second value you supply is the array id.

Here is the whereNotIn query syntax that you can use in Laravel.

whereIn('column name', 'array')
Enter fullscreen mode Exit fullscreen mode
  • Column_name:- Your database table column name.
  • Array: – The column’s value is not contained in the given array. Let’s take look at some examples of whereNotIn() eloquent method in laravel.

Example 1: whereNotIn Query Using Simple SQL Query:

SELECT *  FROM users  WHERE id NOT IN (1, 5, 9)
Enter fullscreen mode Exit fullscreen mode

In this SQL query, the data will not be gotten from the DB table. Whose ids will be 1, 5, 9.

Example 2: Eloquent WhereNotIn Query Using Query Builder

public function users()
{
    return DB::table('users')->whereNotIn('id', [1, 5, 9])->get();
}
Enter fullscreen mode Exit fullscreen mode

Example 3: Eloquent WhereNotIn Query Using Laravel Model

public function users()
{
    return User::whereNotIn('id', [1, 5, 9])->get();
}
Enter fullscreen mode Exit fullscreen mode

So far you have seen in the given example. Have used ids for scaping and getting data into DB table. But now for example 4, we will fetch the data by using the DB table column name.

Example 4: Eloquent WhereNotIn Query Using Laravel Model With Different Column Name

public function users()
{
    return User::whereNotIn('email', ["test@test1.com", "test@test2.com"])->get();
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this article.

Top comments (0)