Can I have a variable number of URI parameters or key-value pairs in Laravel 4?

江枫思渺然 提交于 2019-12-01 23:46:34

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!