Sharjeel Khan
Sharjeel Khan

Reputation: 31

Laravel 5.3 pagination pretty URL for API

Is there a way to get a pagination pretty URL in Laravel 5.3?

For example, by default:

Search keyword is: something new

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..

Upvotes: 0

Views: 843

Answers (1)

Cameron Roe
Cameron Roe

Reputation: 290

You would need to switch the HTTP method used for the search path to send the query string through POST instead of 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.

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/.

Upvotes: 1

Related Questions