Home > OS >  how to use multiple filter in laravel
how to use multiple filter in laravel

Time:10-06

I want to filter data from multiple tables so I write query like that and one thing I let you know that both data1 and data2 return same column with different data.

$data1 = collect(DB::table('table_1')->get()->toArray());
$data2 = collect(DB::table('table_2')->get()->toArray());
$results = $data1->merge($data2);
if ($request->name!="") {
  $results->when(request('name'), function($q){
    $q->Where('name', request('name'));
  });
}
.
.
.
return $results;

But $results returns all data and not filter data

CodePudding user response:

Try this :

$data1 = collect(DB::table('table_1')->get()->toArray());
$data2 = collect(DB::table('table_2')->get()->toArray());
$results = $data1->merge($data2);
if ($request->name!="") {
  $filter_results = $results->when($request->name, function($q){
    $q->where('name', $request->name);
  });
}
.
.
.
return  $filter_results;

CodePudding user response:

Try this

 $data1 = collect(DB::table('table_1')->get()->toArray());
 $data2 = collect(DB::table('table_2')->get()->toArray());
 $results = $data1->merge($data2);

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

return $results;
  • Related