简体   繁体   English

Laravel 5.3 API的分页漂亮URL

[英]Laravel 5.3 pagination pretty URL for API

Is there a way to get a pagination pretty URL in Laravel 5.3? 有没有办法在Laravel 5.3中获得漂亮的分页URL?

For example, by default: 例如,默认情况下:

Search keyword is: something new 搜索关键字是: something new

http://localhost/project/search/something%20new?page=2 http:// localhost / project / search / something%20new?page = 2

{
  "total": 19,
  "per_page": 5,
  "current_page": 1,
  "last_page": 4,
  "next_page_url": "http://localhost/project/search/something%20new?page=2",
  "prev_page_url": null,
  "from": 1,
  "to": 5,
  "data": [
  {
     // result
    }
  ]
}

And what I would like to get: 我想得到的是:

http://localhost/project/search/?page=2

Also, the pagination should render this way, and appending to the pagination should appear in this way. 同样,分页应以这种方式呈现,并且添加到分页应以这种方式出现。

Controller. 控制器。

public function search(Request $request)
{
    $search = $request->name;

    $searchValues = preg_split('/\s+/', $search, -1, PREG_SPLIT_NO_EMPTY);

    $result = abcModel::where( function ($q) use ($searchValues) {
        foreach ($searchValues as $value ) {
            $q->orWhere('city', 'like', "%{$value}%");
            $q->orWhere('country', 'like', "%{$value}%");
            $q->orWhere('name', 'like', "%{$value}%");
             } })
        ->orderby('id','desc')
        ->paginate(20);

    return response()->json( $result );
}

Route, 路线,

Route::post('search/',array('uses' => 'abcController@search'));

Request and Response is above.. 请求和响应在上面。

You would need to switch the HTTP method used for the search path to send the query string through POST instead of GET. 您将需要切换用于搜索路径的HTTP方法,以通过POST(而不是GET)发送查询字符串。 So, without code posted I am assuming you have a route set up like this: 因此,如果没有发布代码,我假设您已经设置了这样的路由:

Route::get('project/search/{query}', 'ExampleController@search');

This would be changed to something like 这将变成类似

Route::post('project/search/', 'ExampleController@search');

As long as you are handling the actual data with the Request object passed into the controller and maintain the same name in the POST body as the GET query parameter, there should be minimal modifications required to your code, if any are needed at all. 只要您使用传递到控制器中的Request对象处理实际数据,并在POST正文中保持与GET查询参数相同的名称,则对代码的修改应该最少,如果有必要的话。

You could take it even further and handle the page parameter in the POST body as well, leaving your URL as http://localhost/project/search/ . 您甚至可以更进一步,并在POST正文中处理page参数,而将URL保留为http://localhost/project/search/

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

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