Home > OS >  Why 'where' return all data in laravel
Why 'where' return all data in laravel

Time:10-06

I am applying search filter in my project so first of all I get data from multiple tables and store in two different variables and then merge these two variable into one so I can filter data from that merged variable. So my code is like that

$data1=Model::query()
   ->Join('...')
   ->leftJoin('...')
   ->where('id',login_user)
   ->select(...)
   ->whereRaw('id IN (select MAX(id) FROM table GROUP BY name)')
   ->groupBy('name')
   ->get();

$data2=Model2::query()
    ->leftJoin(...)
    ->select(...)   
    ->where('id',login_user)
    ->whereNotIn(..)
    ->get(); 

both data1 and data2 return same column with different values so I merge both variable like that

$results = $data1->concat($data2);

No when I already get data so now I need to add filter data from $results so i make post method for that . so When user request to filter data with name I write query like that

if ($request->name!="") {
  $results->when(request('name'), function($q){
    $q->Where('name', request('name'));
  });
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);

But that query is not filtering the data and return me all data.I am new in laravel so I don't know what I have done wrong in that any favour will be helpful for me ,thanks.

CodePudding user response:

if (request()->has('name')) {
  $results->when(request()->get('name'), function($q){
    return $q->where('name', request()->get('name'));
  });
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);

As you use 'when()', you can drop the if expression all together:

$results->when(request()->has('name'), function($q){
    return $q->where('name', request()->get('name'));
});
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);

request() is a Laravel helper for Request $request

Edit: the where() clause in the ORM is with a small 'w', not 'W' as in orWhere

CodePudding user response:

Try this :

if ($request->name) {
    $results->where(function ($q) use ($request) {
        $q->where('name', $request->name)
    });
}
$records = $results;

return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
  • Related