Laravel 4中可以有可变数量的URI参数或键值对吗? [英] Can I have a variable number of URI parameters or key-value pairs in Laravel 4?

查看:76
本文介绍了Laravel 4中可以有可变数量的URI参数或键值对吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个购物车,希望能够传递可变数量的可选参数.诸如:排序依据,过滤依据,包含/排除等.因此,URL可能是:

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/

等等.

我想我可以为所有可能的参数设置一个带有占位符的路由,并在URL中设置默认值,如下所示:

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

但是,这似乎真的很……优雅.有这样做的好方法吗? 我想我也可以尝试编写服务器重写规则来解决这个问题,但是我不喜欢绕过Laravel的想法.

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.

推荐答案

您应将查询字符串(GET参数)用于此类过滤器.使用查询字符串时,参数可以按任何顺序排列,如果不需要,可以轻松跳过.制作一个可以过滤列表的简单表格(使用method="GET")也很容易

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

使用GET参数,URL更像:

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

然后可以使用Input::get('name', 'default')单独检索

GET参数,或者使用Input::all()将其作为集合检索.这也是分页器将页码添加到您的链接中的方式.

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.

这篇关于Laravel 4中可以有可变数量的URI参数或键值对吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆