Side note.
I disagree with @Steve Bauman's idea (in his answer) that one rarely needs querystring urls, and think that Laravel should at least consider adding querystring functionality (back) in. There are plenty of cases when you want a querystring url rather than a param based "pretty url". For example, a complex search filter...
example.com/search/red/large/rabid/female/bunny
...可能指的是与…完全相同的啮齿类动物...
example.com/search/bunny/rabid/large/female/red
但是不管你怎么看(编程、市场分析、搜索引擎优化、用户友好性),它都有点糟糕.尽管...
example.com/search?critter=bunny&gender=female&temperament=rabid&size=large&color=red
...is longer and "uglier", it actually is better in this not-so-rare case. Net: Friendly URLs are great for some things, querystrings are great for others.
Answer to the original question...个
I needed a "querystring" version of url()
-- so I copied the function, modified it, and stuck it in /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;
}
示例:
$url = qs_url('sign-in', array('email'=>$user->email));
//http://example.loc/sign-in?email=chris%40foobar.com
Note: It appears that the url()
function is pluggable, that is, you can replace it. Look in vendor/laravel/framework/src/Illuminate/Support/helpers.php
: the url
function is wrapped in a if ( ! function_exists('url'))
conditional. But you would probably have to jump through hoops to do it (i.e. have laravel load it before its version.)
Cheers,
Chris