Welcome Guest, Not a member yet? Register   Sign In
RESTFul route + search terms via querystring
#1

Dear all,

I would like to add a search method to my restful resource controller.

Currently I have this line in my Config\Routes.php:

PHP Code:
$routes->resource('api/products', ['controller' => 'Api\Products']); 


What should I add to my routes to be able to browse to localhost/api/products/?category=food&maxPrice=10 and to call an underlying Api\Products\Search() method with passing the search term(s) to it.

Thank you
Reply
#2

In the index() method, check for the presence of values. And there you can already call the method or not call it.
Routes only work with a path.
Reply
#3

(06-29-2022, 09:55 AM)iRedds Wrote: In the index() method, check for the presence of values. And there you can already call the method or not call it.
Routes only work with a path.

Well, routes are working with path, but you can still need to use querystrings (typically in a search/filter context).

Finally, I made it with 2 different routes :

App/Config/Routes.php
PHP Code:
$routes->get('api/products/search/''Api\Products::search');
$routes->resource('api/products', ['controller' => 'Api\Products']); 

I can then define a proper search() method within my controller without having to pass thru index()

/App/Controllers/Api/Products.php
PHP Code:
class Products extends ResourceController
{
    public function search()
    {
        $arrFilters $this->request->getVar();

        $res serializer_instance()->toArray(repo_instance()->getProductRepo()->findBy($arrFilters));
        if (!$res) return $this->failNotFound();
        return $this->respond($res);
    }



Note that the search can take several parameters thru the getVar() array so that following call is working /public/api/products/search/?maxprice=10&category=beverages&subcategory=beer
Reply
#4

Yes, your implementation has the right to life.
But from a practical point of view, it does not make sense.
The index method returns the entire list, adding a filter (search) also returns the list. So what's the difference?
Reply




Theme © iAndrew 2016 - Forum software by © MyBB