Laravel 5.1 在 url 中添加查询字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33737615/
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-09-14 12:41:59  来源:igfitidea点击:

Laravel 5.1 add Query strings in url

phplaravellaravel-5.1laravel-routing

提问by Arnab Rahman

I've declared this route:

我已经声明了这条路线:

Route::get('category/{id}{query}{sortOrder}',['as'=>'sorting','uses'=>'CategoryController@searchByField'])->where(['id'=>'[0-9]+','query'=>'price|recent','sortOrder'=>'asc|desc']);

I want to get this in url: http://category/1?field=recent&order=descHow to achieve this?

我想在 url 中得到这个:http://category/1?field=recent&order=desc如何实现?

采纳答案by Wader

Query strings shouldn't be defined in your route as the query string isn't part of the URI.

不应在您的路由中定义查询字符串,因为查询字符串不是 URI 的一部分。

To access the query string you should use the request object. $request->query()will return an array of all query parameters. You may also use it as such to return a single query param $request->query('key')

要访问查询字符串,您应该使用请求对象。$request->query()将返回所有查询参数的数组。您也可以使用它来返回单个查询参数$request->query('key')

class MyController extends Controller
{
    public function getAction(\Illuminate\Http\Request $request)
    {
        dd($request->query());
    }
}

You route would then be as such

您的路线将如此

Route::get('/category/{id}');

Edit for comments:

编辑评论:

To generate a URL you may still use the URL generator within Laravel, just supply an array of the query params you wish to be generated with the URL.

要生成 URL,您仍然可以使用 Laravel 中的 URL 生成器,只需提供您希望使用 URL 生成的查询参数数组。

url('route', ['query' => 'recent', 'order' => 'desc']);

回答by O?uz Can Sertel

if you have other parameters in url you can use;

如果您在 url 中有其他参数,则可以使用;

request()->fullUrlWithQuery(["sort"=>"desc"])

回答by Grzegorz Gajda

Route::get('category/{id}/{query}/{sortOrder}', [
    'as' => 'sorting',
    'uses' => 'CategoryController@searchByField'
])->where([
    'id' => '[0-9]+',
    'query' => 'price|recent',
    'sortOrder' => 'asc|desc'
]);

And your url should looks like this: http://category/1/recent/asc. Also you need a proper .htaccessfile in publicdirectory. Without .htaccessfile, your url should be look like http://category/?q=1/recent/asc. But I'm not sure about $_GETparameter (?q=).

以及您的网址应该是这样的:http://category/1/recent/asc。此外,您还需要目录中的适当.htaccess文件public。如果没有.htaccess文件,您的网址应该类似于http://category/?q=1/recent/asc. 但我不确定$_GET参数 ( ?q=)。