laravel-json-api / laravel

JSON:API for Laravel applications
MIT License
541 stars 41 forks source link

How do you filter for date range? #251

Closed od3n closed 1 year ago

od3n commented 1 year ago

Tried to pass filter[created_at]>=2023-05-01 and filter[created_at]<=2023-06-01 to query params but the query use is select * from "users" where "users"."client_id" = ? and "users"."created_at" >= ? and "users"."created_at" <= ? and "users"."deleted_at" is null {"bindings":["2","2023-06-01","2023-06-01"],"time":46.53}

Looks like it overwrite the first param I passed.

Or should I use custom filter instead?

lindyhopchris commented 1 year ago

The JSON:API specification doesn't define how filters should work - it's down to each implementation.

You'd need to implement your own filter class, as per the docs here: https://laraveljsonapi.io/docs/3.0/schemas/filters.html#writing-filters

You'd probably want to couple that to the filter[created_at] query parameter. Your syntax though of filter[created_at]>=2023-05-01 would not work as it's not a properly formed query parameter. I'd suggest using something like:

filter[created_at][gte]=2023-05-01&filter[created_at][lte]=2023-06-01

Then your filter class would receive an array with gte and lte keys.

MeiKatz commented 1 year ago

I personally use something like the following: filter[created_at:gte]=2023-05-01&filter[created_at:lte]=2023-06-01

od3n commented 1 year ago

I personally use something like the following: filter[created_at:gte]=2023-05-01&filter[created_at:lte]=2023-06-01

mind to share your code? TIA

MeiKatz commented 1 year ago
public function filters(): array {
  return [
    Where::make('created_at')->eq(),
    Where::make('created_at:gt', 'created_at')->gt(),
    Where::make('created_at:lt', 'created_at')->lt(),
    Where::make('created_at:gte', 'created_at')->gte(),
    Where::make('created_at:lte', 'created_at')->lte(),
  ];
}
ben221199 commented 1 year ago

I somehow like this approach.

lindyhopchris commented 1 year ago

Yeah, super simple - nice!