简体   繁体   English

Laravel路径URL查询字符串

[英]Laravel route url with query string

On laravel 4 I could generate a url with query strings using the route() helper.在laravel 4我可以产生与使用route()辅助查询字符串的URL。 But on 4.1 instead of:但在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.我做了一些研究和所有laravel方法生成的URL使用这样的参数。 How can I generate the url with query strings?我怎样才能生成查询字符串的URL?

Laravel's route() and action() helper methods support URL query params. Laravel 的route()action()辅助方法支持 URL 查询参数。 The url() helper method, unfortunately does not.不幸的是, 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'

Basically, any elements in the array that contain string keys will be treated as query parameter ( /products?param=value ).基本上,数组中包含字符串键的任何元素都将被视为查询参数( /products?param=value )。 Anything with an integer key will be treated as a URL argument ( /products/{arg} ).任何带有整数键的内容都将被视为 URL 参数 ( /products/{arg} )。

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 can't use route() or action() , you can generate a URL with query params using the Arr::query() helper:如果您不能使用route()action() ,您可以使用Arr::query()助手生成带有查询参数的 URL:

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'

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".我不同意@Steve鲍曼的想法(他的回答)是一个很少需要查询字符串的URL,并认为Laravel至少应该考虑增加查询字符串的功能(回)。有很多情况下,当你想查询字符串的URL,而不是设置了一个param根据“漂亮网址”。 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

...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.网:友好的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.注:看来, url()函数是可插拔的,也就是说,你可以取代它。 Look in vendor/laravel/framework/src/Illuminate/Support/helpers.php : the url function is wrapped in a if ( ! function_exists('url')) conditional.在查找vendor/laravel/framework/src/Illuminate/Support/helpers.php :该url功能被包裹在一个if ( ! function_exists('url'))的条件。 But you would probably have to jump through hoops to do it (ie have laravel load it before its version.)但是,你或许会通过箍做跳跃(即有laravel加载其之前的版本。)

Cheers,干杯,

Chris克里斯

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());
}

getRouteNames is 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.这会加载您当时注册的所有路由,并立即从 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.您可以轻松传递要为其保留通配符的路由名称的布尔值或“白名单”,这样它就不会无意中踩到 Laravel 默认设置。 Once you run this, it automatically starts working with query string variables, which I find far preferable to path variables in this instance.一旦你运行它,它会自动开始使用查询字符串变量,我发现在这个实例中它比路径变量可取。

A simple way to do this, specially to use with jQuery Autocomplete, it's modify the Controller with a condition to check if has 'term' in the $request:一个简单的方法来做到这一点,特别是与 jQuery 自动完成一起使用,它是修改控制器的条件来检查 $request 中是否有“term”:

(Controller file) (控制器文件)

public function list_for_autocomplete(Request $request)
{
    if ($request->has('term')) {
        return YourModel::select('column_name as value')
            ->where('column_name', 'like', '%' . $request->input('term') . '%')
            ->get()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM