Reputation: 43
how can I make a fancy filtering in Lumen API using query builder? For example I would like to filter my products like this: http://localhost:8000/products?product_group=network
This is my controller:
public function index(){
$tlt_product_groups = DB::table('tlt_products')->groupBy('product_group')->get()->toArray();
$tlt_products = DB::table('tlt_products')->get()->groupBy('product_group')->toArray();
return response()->json([
'categories'=> $tlt_product_groups,
'products' =>$tlt_products
]);
}
And this is my route:
$router->get('products','ProductController@index');
Upvotes: 0
Views: 771
Reputation: 6544
Before you don't call get()
on the query, it is still a query object and can be transformed further. You don't have to write the whole query in one piece. Therefore you should be able to do something like:
public function index(\Illuminate\Http\Request $request) {
$query = DB::table('tlt_products');
if ($request->has('product_group')) {
$query = $query->where('product_group', $request->get('product_group'));
}
$products = $query->get();
return response()->json([
'categories'=> $tlt_product_groups,
'products' =>$tlt_products,
]);
}
If you want to extend your filtering, you can also allow filtering on multiple columns without having to write the code for each new column again:
public function index(\Illuminate\Http\Request $request) {
$filterColumns = ['product_group', 'price', 'manufaturer'];
$query = DB::table('tlt_products');
foreach ($filterColumns as $column) {
if ($request->has($column)) {
$query = $query->where('product_group', $request->get($column));
}
}
$products = $query->get();
return response()->json([
'categories'=> $tlt_product_groups,
'products' =>$tlt_products,
]);
}
Upvotes: 2