且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel带有查询字符串的路由URL

更新时间:2023-02-26 11:34:10

旁注.

我不同意@Steve Bauman的想法(在他的回答中),很少有人需要查询字符串url,并认为Laravel至少应考虑添加查询字符串功能(返回).在很多情况下,您想要查询字符串url而不是而不是基于参数的漂亮网址".例如,一个复杂的搜索过滤器...

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

...可能潜在地指的是与...完全相同的啮齿动物组.

...may potentially refer to the same exact set of rodents as...

example.com/search/bunny/rabid/large/female/red

...但是从任何角度看(编程,市场分析,SEO,用户友好),这都太糟糕了.即使...

...but any way you look at it (programming, marketing analytics, SEO, user-friendliness), it's kinda terrible. Even though...

example.com/search?critter=bunny&gender=female&temperament=rabid&size=large&color=red

...更长,更丑",实际上在这种不太常见的情况下更好.网路:友善的URL在某些方面非常有用,查询字串在其他方面非常有用.

...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.

原始问题的答案...

我需要url()的查询字符串"版本-所以我复制了函数,对其进行了修改,然后将其粘贴在/app/start/global.php中:

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

注:url()函数似乎是可插入的,也就是说,您可以替换它.在vendor/laravel/framework/src/Illuminate/Support/helpers.php中查找:url函数包装在if ( ! function_exists('url'))条件中.但是您可能必须跳过箍才能做到这一点(即在版本发布之前先让laravel加载它).

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.)

干杯

克里斯