在laravel 4上,我可以使用route()帮助器生成带有查询字符串的url.但是在4.1而不是:
$url = url('admin.events', array('lang' => 'en'));
// admineventsurl/?lang=en
Run Code Online (Sandbox Code Playgroud)
我明白了:
$url = url('admin.events', array('lang' => 'en'));
// admineventsurl/en
Run Code Online (Sandbox Code Playgroud)
我做了一些研究,生成url的所有laravel方法都使用这样的参数.如何使用查询字符串生成网址?
Ste*_*man 43
Laravel route()
和action()
helper方法支持URL参数.
只需为路径参数提供一个包含键值的数组.例如:
route('products.index', ['manufacturer' => 'Samsung']);
// Returns 'http://localhost/products?manufacturer=Samsung'
Run Code Online (Sandbox Code Playgroud)
您还可以包含这些参数附带的路径参数(例如ID和模型):
route('products.show', [$product->id, 'model' => 'T9X']);
// Returns 'http://localhost/products/1?model=T9X'
Run Code Online (Sandbox Code Playgroud)
动作方法也支持这一点:
action('ProductController@index', ['manufacturer' => 'Samsung']);
Run Code Online (Sandbox Code Playgroud)
您还可以在url()
和link_to_route()
方法中提供查询参数:
link_to_route('products.index', 'Products by Samsung', ['model' => 'Samsung');
link_to_action('ProductController@index', 'Products by Samsung', ['model' => 'Samsung']);
Run Code Online (Sandbox Code Playgroud)
小智 32
边注.
我不同意@Steve Bauman的想法(在他的回答中),很少需要查询字符串,并且认为Laravel至少应该考虑添加查询字符串功能(返回).有很多情况下你想要一个查询字符串而不是一个参数基于"漂亮的网址".例如,复杂的搜索过滤器......
example.com/search/red/large/rabid/female/bunny
Run Code Online (Sandbox Code Playgroud)
......可能潜在地指同一组啮齿动物......
example.com/search/bunny/rabid/large/female/red
Run Code Online (Sandbox Code Playgroud)
...但是你看它的任何方式(编程,营销分析,搜索引擎优化,用户友好性),它有点可怕.即使...
example.com/search?critter=bunny&gender=female&temperament=rabid&size=large&color=red
Run Code Online (Sandbox Code Playgroud)
...更长,更"丑陋",在这个不那么罕见的情况下,它实际上更好.网:友情网址对某些东西很有用,查询字符串对其他人来说很棒.
回答原来的问题......
我需要一个"querystring"版本url()
- 所以我复制了这个函数,修改了它,并将其粘贴在/app/start/global.php
:
/**
* Generate a querystring url for the application.
*
* Assumes that you want a URL with a querystring rather than route params
* (which is what the default url() helper does)
*
* @param string $path
* @param mixed $qs
* @param bool $secure
* @return string
*/
function qs_url($path = null, $qs = array(), $secure = null)
{
$url = app('url')->to($path, $secure);
if (count($qs)){
foreach($qs as $key => $value){
$qs[$key] = sprintf('%s=%s',$key, urlencode($value));
}
$url = sprintf('%s?%s', $url, implode('&', $qs));
}
return $url;
}
Run Code Online (Sandbox Code Playgroud)
例:
$url = qs_url('sign-in', array('email'=>$user->email));
//http://example.loc/sign-in?email=chris%40foobar.com
Run Code Online (Sandbox Code Playgroud)
注意:该url()
功能似乎是可插拔的,也就是说,您可以替换它.查看vendor/laravel/framework/src/Illuminate/Support/helpers.php
:url
函数包含在if ( ! function_exists('url'))
条件中.但你可能不得不跳过箍来做这件事(即在其版本之前将laravel加载它.)
干杯,
克里斯
归档时间: |
|
查看次数: |
65022 次 |
最近记录: |