mysql – Laravel 5.6 consulta whereNotExist


I have a practice where cars must be added to an insurer and be able to register their insurance, and I am trying to make a query that, when selecting an insurer from a list, will return all the vehicles that are not in that insurer (including those that are in others), but running it does not return anything.

This would be the function in the controller:

public function mostrarVehNAs(Request $request){
            $aseguradora = 2;
            $datos = \DB::table('crlo_vehiculos')
            ->whereNotExists(function ($query) {
                $aseguradora = 2;
                      ->whereRaw('crlo_veh_asegurados.id_aseguradora', '=', $aseguradora);
            return $datos;

The tables would be:


| id_aseguradora | nom | direccion |


| id_vehiculo | marca | modelo | ano | tipo | color | serial |


| id_aseg | id_vehiculo | id_aseguradora | id_vigencia |

I'm new to laravel, so I still don't quite understand how to structure the query.

Thanks in advance for your answers.


Did you try using the whereNotIn method of the Where Clauses ?

$aseguradora_id = 2;
$veh_asegurados = DB::table('veh_asegurados')
                    ->whereNotIn('id_aseguradora', [$aseguradora_id])

I think the above code is what you are needing but if what you need is the vehicles from the vehiculos table you could obtain the vehicle ids to obtain the info using the whereIn method

$aseguradora_id = 2;
$veh_asegurados_ids = DB::table('veh_asegurados')
                    ->whereNotIn('id_aseguradora', [$aseguradora_id])

$vehiculos = DB::table('vehiculos')
                    ->whereIn('id', $veh_asegurados_ids)
Scroll to Top