简体   繁体   中英

Lumen API fancy filtering

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');

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,
    ]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM