Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jake2025's avatar

DB::Select to Eloquent

Greetings,

Can someone help me change this code to eloquent? if there's a simple code of eloquent for this.

$locations = DB::select('SELECT * FROM inv_locations WHERE id NOT IN (SELECT location_id FROM inv_devices WHERE item_id = '.$id.')');

Thanks!

0 likes
5 replies
Marwelln's avatar
Level 4

Try this (not tested, just from guess):

$locations = InvLocation::whereNotIn('id', function($query) use ($id) {
    $query->table = 'inv_devices';
    $query->select(['location_id']); 
    $query->where('item_id', $id); 
})->get();
2 likes
jake2025's avatar

It throws an exception:

Missing argument 2 for Illuminate\Database\Query\Builder::whereNotIn()

jake2025's avatar

Still error XD.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where `item_id` = ?)' at line 1 (SQL: select * from `inv_locations` where `id` not in (select `location_id` where `item_id` = 1))
jake2025's avatar

Fixed it. I added

$locations = Location::whereNotIn('id', function($query) use ($id) {
         $query->select(['location_id']); 
         $query->from('devices');
         $query->where('item_id', $id); 
      })->get();

from and removed table. Thanks sir!

1 like

Please or to participate in this conversation.