panthro's avatar

Filtering a resource with query string or use an endpoint?

If I had a series of posts from my post model and I wanted to get the trending posts or perhaps only display posts from a certain category, should I:

  1. Pass a query param to do the filtering to my post controller?
  2. Have an endpoint and specific controller, e.g. /posts/trending, /posts/movies.

Thanks!

0 likes
4 replies
Zain_Zulifqar's avatar

It totally depends on your requirement and app structure if you are using vue client or mobile app then surely goes with api end point. if you want to avoid page refresh or you think in future you will need endpoint for some other uses then create end point otherwise i dont think you need specific controller and endpoint for just a normal filter

2 likes
martinbean's avatar

@panthro They seem to just be filters for the same resource (posts). So you could just have filters for them:

  • /api/posts?filter[scope]=trending
  • /api/posts?filter[category]=movies

This way you don’t need multiple controllers for doing the same thing (listing posts), nor do you need to create a brand new endpoint URI and controller to add any more filters; you just create the filter and can then access it through the existing, generic posts controller’s index action.

Spatie (of course) has a helpful package for doing just this (converting query string parameters to Eloquent query builder clauses): https://spatie.be/docs/laravel-query-builder/v3

2 likes
jlrdw's avatar

@panthro well here of forum if I filter by Popular this week, it's just a change of parameters to retrieve those records. I can't imagine Jeffrey having 10 different end points for the different links on the left.

So a query string or passed parameters either will work, and use scopes when needed.

Just suggestion.

popular this week - https://laracasts.com/discuss?trending=1
popular all time - https://laracasts.com/discuss?popular=1

As you can see a query string is used.

2 likes
panthro's avatar

Thank you all! I suspect I will go with some sort of query filter, also thank you @martinbean for the spatie link - I will check it out.

Please or to participate in this conversation.