CodeIgniter Forums
RESTFul route + search terms via querystring - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: RESTFul route + search terms via querystring (/showthread.php?tid=82315)



RESTFul route + search terms via querystring - b126 - 06-29-2022

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


RE: RESTFul route + search terms via querystring - iRedds - 06-29-2022

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.


RE: RESTFul route + search terms via querystring - b126 - 06-30-2022

(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


RE: RESTFul route + search terms via querystring - iRedds - 06-30-2022

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?