在laravel 4上,我可以使用route()助手生成带有查询字符串的url.但在4.1上,而不是:

$url = url('admin.events', array('lang' => 'en'));
// admineventsurl/?lang=en

I get:

$url = url('admin.events', array('lang' => 'en'));
// admineventsurl/en

我做了一些研究,所有生成url的laravel方法都使用了这样的参数.如何生成带有查询字符串的url?

推荐答案

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

Laravel相关问答推荐

密码确认在Livewire中不匹配

查询Laravel中的图形

Laravel 数据未传递到下拉框

在 laravel 中查询此类数据的最佳做法是什么?

Laravel:如何通过 id 从集合中删除项目

使用 Laravel 和 Passport 验证失败时响应状态码 401?

带有 Laravel Passport 的 SSO

函数 mcrypt_get_iv_size() 在 Laravel 4 上已弃用

Laravel 5 - 多对多 - Attach versus Save

在 Laravel 中生成随机数

禁用Eager的关系

在 Laravel 测试用例中模拟一个 http 请求并解析路由参数

改变模式生成器中的列长度?

Class类 App\Http\Controllers\Auth\Request 不存在.

Laravel 4:将什么作为参数传递给 Url 类?

如何在没有日志(log)、没有信息的情况下调试 Laravel 错误 500

如果在 Laravel 5.1 中找不到路由,则显示 404 页面

带有 Xdebug 的 Laravel 5 总是抛出The payload is invalid..

错误:找不到模块 'webpack/lib/rules/DescriptionDataMatcherRulePlugin' 需要堆栈:

函数参数前的三个点代表什么?