简体   繁体   English

Laravel RESTful URL参数处理

[英]Laravel RESTful url parameters handling

I am designing a RESTful application and I would like to manage url parameters, at the moment I have this function in controller for the GET that list all the resources api/v1/cats: 我正在设计一个RESTful应用程序,并且我想管理url参数,目前我在GET控制器中具有此功能,该功能列出了api / v1 / cats的所有资源:

public function index()
{
    $cats = Cats::all();

    foreach ($cats as $cat) {
        $requirement->view_requirement = [
                'href' => 'api/v1/cat/' . $cat->id,
                'method' => 'GET'
        ];
    }

    $response = [
            'msg' => 'List of all Cats',
            'cats' => $cats
    ];
    return response()->json($response, 200);
}

and route is : 路线是:

Route::group(['prefix' => 'v1'], function() {

Route::resource('cats', 'CatController', [
        'except' => ['edit', 'create']
]);

which is the best way to manage url with for example search parameter like: api/v1/cats?name=Filip&color=black 这是使用例如api / v1 / cats?name = Filip&color = black这样的搜索参数来管理url的最佳方法

you should not add any thing to the route file to handle request params just catch them in the controller as \\Input::all() 您不应该在路由文件中添加任何内容来处理请求参数,只需将它们作为\\Input::all()捕获到控制器中即可

then you can search and retrieve the result. 然后您可以搜索和检索结果。

any you can use this to handle search on model level 任何您可以使用它来处理模型级别的搜索

https://github.com/nicolaslopezj/searchable https://github.com/nicolaslopezj/searchable

To retrieve GET parameters you can do both ways : 要检索GET参数,您可以执行以下两种方式:

  • TypeHint the Request class (global namespace) to inject the Request object and get your parameter via $request->get('filter') TypeHint Request类(全局名称空间)以注入Request对象并通过$request->get('filter')获取参数
  • Use the request() helper function this way request()->get('filter') or the shortcut 'request('filter') 以这种方式使用request()辅助函数request()->get('filter')或快捷方式'request('filter')

Little tips about REST APIs : I don't know the stage of development of your project, but there are some guidelines / best practises for REST APIs and I highly encourage you to follow them. 关于REST API的小技巧:我不知道您的项目的开发阶段,但是有一些REST API的准则/最佳实践,我强烈建议您遵循它们。 It will guide and help you making an awesome, robust, maintenable API. 它将指导并帮助您制作一个很棒的,健壮的,可维护的API。 Speaking of experiences ;) 说到经验;)

Here is an example : http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api 这是一个示例: http : //www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

EDIT : You can of course still use $_GET 编辑:您当然仍然可以使用$_GET

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

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