[SOLVED] How to write a where not in query in laravel?

Issue

I want to write a Where not in query in laravel. I wrote in sql it’s working fine please help me convert the query to laravel.

This is the query…

SELECT * 
FROM `apiaccessauth` 
WHERE `site_name` NOT IN (
                SELECT `site_name` 
                FROM `API_site_access_log` 
                WHERE `created_at` LIKE '%2021-10-15%'
                );

Solution

If you want to use Eloquent, it’ll be like below

Eloquent model

<?php

namespace App\Modules\Vehicle\Models;

use Illuminate\Database\Eloquent\Model;

class ApiAccessAuth extends Model
{
    protected $table = 'apiaccessauth';
}

Your query

ApiAccessAuth::whereNotIn('site_name', function ($query) {
    $query->from('API_site_access_log')
        ->select('site_name')
        ->whereDate('created_at', '2021-10-15');
})->get();

If you want to use query builder, it’ll be like below

use Illuminate\Support\Facades\DB;

DB::table('apiaccessauth')
    ->whereNotIn('site_name', function ($query) {
        $query->from('API_site_access_log')
            ->select('site_name')
            ->whereDate('created_at', '2021-10-15');
    })->get();

Answered By – sithuaung

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published.