Laravel 7|8 WhereNotIn Database Query Examples

Last updated on by Digamber

When it comes to the smooth execution of database queries, then laravel tops on the list. It has the best database query builder that eases your database operations.

This is a quick tutorial that helps you write laravel database queries. In this example, we will cover laravel eloquent where not in the database query.

So in this tutorial, i am going to manifest the easy way to deal with the wherenotin query in laravel.

Read more: How to Use WhereIn Query in Laravel

Laravel Eloquent “WHERE NOT IN” Query Examples

The wherenotin() database query method takes two parameters. The first argument you pass 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')

Now, i am going to enumerate few examples through which the entire picture will be cleared.

Query Builder Example

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class MyController extends Controller
{

    public function index()
    {
        $users = DB::table('students')
            ->whereNotIn('name', ['6', '5', '4'])
            ->get();

        return view('home', ['students' => $students]);
    }

}

Laravel eloquent “Where not in” query makes sure that the provided column’s value is not included in the given array:

The SQL wherenotin query in laravel is mainly used with an array. If you want to utilize the SQL wherenotin query, you can go for the wherenotin() query method.

The laravel query builder is based on the PDO parameter that gives more power to security and protects from evil SQL injection attacks.

WhereNotIn Example with Laravel Model:

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Students;

class MyController extends Controller
{

    public function index()
    {
        $users = Students::table('students')
            ->whereNotIn('name', ['John', 'Randy', 'Harry'])
            ->get();

        return view('home', ['students' => $students]);
    }

}