Home > Enterprise >  Create laravel api with page and limit results
Create laravel api with page and limit results

Time:02-18

I want to create an api with limit and page number, I am trying to use the api to load more data on scroll in my app.

Question 1: How can I limit the result, per each page.

For example https://placewave.com/allusers?results=10&page=2

The URL above the page=2 show the second page with results=10 10 fetch result for page 2, same thing for page 3 with 10 result.

My Code

public function allUser(Request $request)
{
    $pageno = $request->pageno;
    return Users::where('active', 'online')
        ->limit(10)->offset($pageno)
        ->get();
}

CodePudding user response:

->paginate($request->get('results', 10))

CodePudding user response:

Laravel's Pagination already handles limit and offset by passing the number of records you'd like per-page, and by examining the page=X query string parameter. So, you can rewrite your code as follows:

public function allUser(Request $request) {
  return Users::where('active', 'online')->paginate($request->input('results', 10));
}

You'll likely want to provide some validation too, to prevent bad actors from messing with your results parameter:

public function allUser(Request $request) {
  $perPage = $request->input('results', 10);
  if (!is_numeric($perPage)) {
    $perPage = 10;
  }

  return Users::where('active', 'online')->paginate($perPage);
}
  • Related