Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel where clause is not working after multiple orWhere clauses?

I am querying vehicles with model name and type but these where clauses are not at the end after addingorWhere. When I comment or remove these orWhere Clauses then its work.

$models = Vehicle::join('vmodels', 'vmodels.vehicle_id', '=', 'vehicles.id')
    ->join('vehicletypes', 'vehicletypes.id', '=', 'vehicles.vehicletype_id')
    ->join('brands', 'brands.id', '=', 'vehicles.make')
    ->join('companies', 'brands.id', '=', 'companies.name')
    ->select('vehicles.slug as vslug', 'brands.name as brandname', 'vehicles.id as vid', 'vmodels.*', 'vehicletypes.name as vtype', 'companies.status as cstatus')
    ->where('brands.name', 'LIKE', "%{$term}%")
    ->orWhere('vmodels.name', 'LIKE', "%{$term}%")
    ->orWhere('vmodels.year', 'LIKE', "%{$term}%")
    ->orWhere('vehicletypes.name', 'LIKE', "%{$term}%")
    ->orWhere('vehicles.model', 'LIKE', "%{$term}%")
    ->where('companies.status', '=', 1 )
    ->where('vmodels.status', '=', 1)
    ->where('vehicles.status', '=', 1)
    ->paginate(30);
like image 208
Amir Ur Rehman Avatar asked Jan 01 '23 09:01

Amir Ur Rehman


2 Answers

Group your orWhere's like,

$models = Vehicle::join('vmodels', 'vmodels.vehicle_id', '=', 'vehicles.id')
    ->join('vehicletypes', 'vehicletypes.id', '=', 'vehicles.vehicletype_id')
    ->join('brands', 'brands.id', '=', 'vehicles.make')
    ->join('companies', 'brands.id', '=', 'companies.name')
    ->select('vehicles.slug as vslug', 'brands.name as brandname', 'vehicles.id as vid', 'vmodels.*', 'vehicletypes.name as vtype', 'companies.status as cstatus')
    ->where(function($query) use($term){
        $query->where('brands.name', 'LIKE', "%{$term}%")
            ->orWhere('vmodels.name', 'LIKE', "%{$term}%")
            ->orWhere('vmodels.year', 'LIKE', "%{$term}%")
            ->orWhere('vehicletypes.name', 'LIKE', "%{$term}%")
            ->orWhere('vehicles.model', 'LIKE', "%{$term}%");
    })
    ->where('companies.status', '=', 1 )
    ->where('vmodels.status', '=', 1)
    ->where('vehicles.status', '=', 1)
    ->paginate(30);

Reference : https://laravel.com/docs/5.7/queries#parameter-grouping

like image 102
Ijas Ameenudeen Avatar answered Jan 05 '23 03:01

Ijas Ameenudeen


if you want to simulate AND/OR statement for your SQL queries with Laravel query builder, you should do it like this:

((A or B) and (C or D)) or (E)

ModelName::join(...)->join(...)
           ->where(function($query){
               $query->where( A )
               ->orWhere( B )
           })
           ->where(function($query){
               $query->where( C )
               ->orWhere( D )
           })->orWhere( E )
like image 44
Mehrdad Mahdian Avatar answered Jan 05 '23 03:01

Mehrdad Mahdian