php 带有查询字符串的 Laravel 路由 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21632835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:18:14  来源:igfitidea点击:

Laravel route url with query string

phplaravel

提问by Diego Castro

On laravel 4 I could generate a url with query strings using the route() helper. But on 4.1 instead of:

在 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

I did some research and all laravel methods to generate url are using the parameters like that. How can I generate the url with query strings?

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

回答by Steve Bauman

Laravel's route()and action()helper methods support URL params. The url()helper method, unfortunately does not.

Laravelroute()action()辅助方法支持 URL 参数。url()不幸的是,辅助方法没有。

Simply provide an array with key values to the route parameters. For example:

只需为路由参数提供一个包含键值的数组。例如:

route('products.index', ['manufacturer' => 'Samsung']);

// Returns 'http://localhost/products?manufacturer=Samsung'

You can also still include your route parameters (such as ID's and models) to accompany these parameters:

您还可以包含路由参数(例如 ID 和模型)以伴随这些参数:

route('products.show', [$product->id, 'model' => 'T9X']);

// Returns 'http://localhost/products/1?model=T9X'

This is also supported in action methods:

这在操作方法中也受支持:

action('ProductController@index', ['manufacturer' => 'Samsung']);

You can also supply query parameters inside the link_to_route()and link_to_action()methods:

您还可以在link_to_route()link_to_action()方法中提供查询参数:

link_to_route('products.index', 'Products by Samsung', ['model' => 'Samsung');

link_to_action('ProductController@index', 'Products by Samsung', ['model' => 'Samsung']);

2019 - EDIT:

2019 - 编辑

If you don't have route names, or don't like using action()simply use:

如果您没有路线名称,或者不喜欢使用action()简单的使用:

url('/products?').\Illuminate\Support\Arr::query(['manufacturer' => 'Samsung']);

// Returns 'http://localhost/products?manufacturer=Samsung'

Or:

或者:

url('/products?').http_build_query(['manufacturer' => 'Samsung'], null, '&', PHP_QUERY_RFC3986);

// Returns 'http://localhost/products?manufacturer=Samsung'

Or create a simple helper function:

或者创建一个简单的辅助函数:

use Illuminate\Support\Arr;
use Illuminate\Support\Str;

function url_query($to, array $params = [], array $additional = []) {
    return Str::finish(url($to, $additional), '?') . Arr::query($params);
}

Then call it:

然后调用它:

url_query('products', ['manufacturer' => 'Samsung']);

// Returns 'http://localhost/products?manufacturer=Samsung'

url_query('products', ['manufacturer' => 'Samsung'], [$product->id]);

// Returns 'http://localhost/products/1?manufacturer=Samsung'

回答by Chris Carson

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

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

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

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

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

...更长,更“丑”,在这种并不罕见的情况下实际上更好。Net:友好的 URL 对某些事情很有用,查询字符串对其他事情也很好。

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:

我需要一个“查询字符串”版本的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;
}

Example:

例子:

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

注:看来该url()功能是可插拔的,也就是可以替换。查看vendor/laravel/framework/src/Illuminate/Support/helpers.php:该url函数包含在if ( ! function_exists('url'))条件中。但是你可能不得不跳过箍来做它(即在它的版本之前让 laravel 加载它。)

Cheers,

干杯,

Chris

克里斯

回答by Tim

The following was what I needed to do:

以下是我需要做的:

I handle all of my routing in a service provider, where I had defined the following function:

我在服务提供者中处理我的所有路由,在那里我定义了以下函数:

private function registerRestfulController($prefix, $controllerClass)
{
    Route::controller($prefix, $controllerClass, $controllerClass::getRouteNames());
}

getRouteNamesis a static method on my BaseController that conventionally returns routes so that RESTful controllers can have automatic named routes.

getRouteNames是我的 BaseController 上的静态方法,它通常返回路由,以便 RESTful 控制器可以具有自动命名路由。

The problem I was running into was that this defined the set of wildcard matchers on the route itself - in order to avoid that, I add the following to the private function above:

我遇到的问题是这定义了路由本身上的通配符匹配器集 - 为了避免这种情况,我将以下内容添加到上面的私有函数中:

foreach ($controllerClass::getRoutesNames() as $name) { 
    $route = Route::getRoutes()->getByName($name);
    $cleanUri = preg_replace('/\/\{\w*\?\}/', '', $route->getUri());
    $route->setUri($cleanUri);
}

This loads all the routes you are registering at the time and immediately removes wildcards from the URI. You could easily pass a boolean or "white-list" of route names that you want to preserve wildcards for, so that it doesn't stomp all over the Laravel default without the intention. Once you run this, it automatically starts working with query string variables, which I find farpreferable to path variables in this instance.

这会加载您当时注册的所有路由,并立即从 URI 中删除通配符。您可以轻松传递要为其保留通配符的路由名称的布尔值或“白名单”,这样它就不会无意中踩到 Laravel 默认设置。一旦你运行它,它会自动开始使用查询字符串变量,我发现在这个实例中它比路径变量可取。