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


Laravel 5.1 add Query strings in url

我已经声明了这个路由:

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

我想在url中获取此:http://category/1?field=recent&order=desc如何做到这一点?

如果url中有其他参数可以使用;

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

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

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

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

你的路线会是这样的

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

编辑评论:

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

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

你的url应该是这样的:http://category/1/recent/asc。此外,您还需要public目录中的一个适当的.htaccess文件。如果没有.htaccess文件,您的url应该看起来像http://category/?q=1/recent/asc。但我不确定$_GET参数(?q=)。