Progressive queries in the controller (good design practices)?

Say for example you receive an API request to list Users as a JSON object. Pretty straightforward to do in the controller class.

Users::all()

Now, the client can pass all sorts of optional arguments in the request, e.g.
minAge, maxAge, gender etc…

These will require additional where conditions in the query. The challenge is to do it optimally, and concisely. Insert the relevant where statements only if the relevant parameters are supplied in the request.

I am looking for examples of handling this design problem in a good way.

EDIT: The aim is also efficiency, minimizing number of database roundtrips.

Thanks

Your issue is the same thing as populating a dynamic table like Sprunje does. Optimization is actually something that needs to be implemented in Sprunje.

It depends on the size of the data and how often it can change. One solution could be quering all the Users, cache the collection and afterward retrieve the collection from cache and apply the filter/sort there. Cache is file based (or memory based when using Redis) and pretty fast. The actual filtering is then done by PHP. But I don’t know how more efficient it can be compare to querying the db each time.

This is exactly what Sprunje does already. See https://github.com/userfrosting/UserFrosting/blob/master/app/sprinkles/core/src/Sprunje/Sprunje.php#L364-L375