I’ve created a filter method for filtering the products list. This is my URL:
localhost/myshop/products/filter?category=shirts&color=blue&page=1
But I want to show this way:
localhost/myshop/products/shirts/blue/1
How can I achieve it?
I’ve created a filter method for filtering the products list. This is my URL:
localhost/myshop/products/filter?category=shirts&color=blue&page=1
But I want to show this way:
localhost/myshop/products/shirts/blue/1
How can I achieve it?
2
Answers
Assuming that
Products::filter()
is responsible for handling the request, you can rewrite the method to accept parameters in its signature. So, if the current logic is something like this:You can simply refactor it to accept parameters through URL segments:
With this in place, your current URL is:
We need to get rid of that extra
filter/
and we’re done, right? Quoting from the docs:OK, so we need to remap the current route. You have a few options:
First, is to update your
application/config/routes.php
file with a new entry:It says that if a URL starts with
products/
, remap it to thefilter
method ofproducts
class.Here you can use wildcards and regex patterns to be even more precise about the type of parameters your method accepts.
Another option is that you might want to implement a
_remap()
method in your controller in order to do the route remapping for you.in
routes.php
file, you can write following lineand function will be like following