I've got a shopping cart that I'd like to be able to pass a variable amount of optional parameters. Things like: sort by, filter by, include/exclude etc. So the URL may be:
/products
/products/sort/alphabetically
/products/filter/cloths
/products/socks/true
/products/sort/alphabetically/socks/true/hats/false/
Etc.
I suppose I could have a route with placeholders for all of the possible parameters and set default values in the URL, so something like:
Route::get('products/sort/{$sort?}/filter/{$filter?}/socks/{$socks?}/hats/{$hats?}/...', function($sort = 'alphabetically', $filter = false, $socks = true, $hats = true, ...)
{
...
});
Then for instance to just exclude hats I'd have to have a URL as follow:
/products/sort/alphabetically/filter/false/socks/true/hats/false
But that seems really... inelegant. Is there a good way of doing this? I suppose I could also try to write a server rewrite rule to account for that, but I don't like the idea of circumventing Laravel.
You should use the query string (GET parameters) for filters like those. When you use the query string parameters can be in any order and can be easily skipped if they're not needed. It's also very easy to make a simple form (with method="GET"
) that can filter your list
With GET parameters a URL would look more like:
/products
/products?sort=alphabetically
/products?filter=cloths
/products?socks=true
/products?sort=alphabetically&socks=true&hats=false
GET parameters can then be retrieved individually with Input::get('name', 'default')
or as a collection with Input::all()
. This is also how the paginator will add the page number to your links.
来源:https://stackoverflow.com/questions/15777947/can-i-have-a-variable-number-of-uri-parameters-or-key-value-pairs-in-laravel-4