laravel 带有查询字符串和自定义参数的“获取”路由

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

"Get" route with query string and custom params

laravellaravel-5.5

提问by Blagoh

I am using Laravel 5.5.13.

我正在使用 Laravel 5.5.13。

My goal is to create an endpoint like this:

我的目标是创建一个这样的端点:

/api/items/{name}?kind={kind}

Where kindis optional parameter passed in by the query string.

kind查询字符串传入的可选参数在哪里。

My current routes in api.phplooks like this:

我目前的路线api.php是这样的:

Route::get('items', 'DisplaynameController@show'); 

My current controller is like this:

我现在的控制器是这样的:

public function show(Request $request)
{
    if ($request->input('kind') {
        // TODO
    } else {
        return Item::where('name', '=', $request->input('name'))->firstOrFail();
    }
}

I

一世

I am currently using $request->input('name')but this means I need to provide ?name=blahin the query string. I am trying to make it part of the route.

我目前正在使用,$request->input('name')但这意味着我需要?name=blah在查询字符串中提供。我正在努力使它成为路线的一部分。

May you please provide guidance.

请各位指导。

回答by Kenny Horna

The $namevariable is a route param, not a query param, this means that you can pass it directly to the function as an argument.

$name变量是路由参数,而不是查询参数,这意味着您可以将其作为参数直接传递给函数。

So, if your route is like this:

所以,如果你的路线是这样的:

Route::get('items/{name}', 'DisplaynameController@show'); 

Your function should be like this:

你的函数应该是这样的:

public function show(Request $request, $name) // <-- note function signature
{   //                                 ^^^^^
    if ($request->has('kind'))
    {
        // TODO
    }
    else
    {
        return Item::where('name', '=', $name)->firstOrFail(); // <-- using variable
    }   //                              ^^^^^
}


Another option is to get the variable as a Dynamic Propertylike this:

另一种选择是将变量作为动态属性获取,如下所示:

public function show(Request $request)
{
    if ($request->has('kind'))
    {
        // TODO
    }
    else
    {
        return Item::where('name', '=', $request->name)->firstOrFail();
    }   //                              ^^^^^^^^^^^^^^
}

Notice that we access the namevalue as a dynamic property of the $requestobject like this:

请注意,我们将name值作为$request对象的动态属性进行访问,如下所示:

$request->name


For more details, check the Routing > Route parametersand Request > Retrieving inputsections of the documentation.

有关更多详细信息,请查看文档的Routing > Route parametersRequest > Retrieving input部分。

回答by ka_lin

As stated in the documentationyou should do:

文档中所述,您应该执行以下操作:

public function show($name, Request $request)

Laravel will take care of the variable binding

Laravel 会处理变量绑定