How can I use or create a pagination in REST API in Laravel?

Viewed 19566

I would like to create a pagination in Rest API for Laravel. I want pagination like, Suppose I have total 30 categories in Database & I want to display 10 items in each page So total page will be 3 and 10 items will display in each page.

I have used paginate() method but it's only showing items by given number , I used below the script but it's not provided output that I mentioned.

$getCategories = Category::paginate();
$listCat = array();
    foreach($getCategories as $val){
        $cateName['id'] = $val->id;
        $cateName['name'] = $val->name;
        $cateName['description'] = $val->description;
        $cateName['image'] = url('/').'/public/assets/images/category/'.$val->image;
        $listCat[] = $cateName;
    }
    
    if(!empty($listCat)){
        $respons['status'] = 'true';
        $respons['message'] = 'Categories list';
        $respons['data list']=$listCat;
    }else{
       $respons['status'] = 'false';
       $respons['message'] = 'Category is not found.'; 
    }
return Response::json($respons,200);

Does anybody tell me how could i use pagination in Rest Api?

I got output like..

enter image description here

4 Answers

for REST pagination you can use code like this

    $data = Category::paginate(request()->all());    
    return Response::json($data, 200);

then you will see at the bottom of data, they will show the pagination info for you

enter image description here

After this:

$getCategories = Category::All();
$categories = DB::table('category')->paginate($pageNumber);

Return it as:

return response()->json($categories, 200);

In your json response you will see "next_page_url" to go second page or vice versa "prev_page_url".

Method 1:

$limit = $request->limit ? $request->limit : 20;
$page = $request->page && $request->page > 0 ? $request->page : 1;
$skip = ($page - 1) * $limit;

$getCategories = Category::slice($skip, $limit);

Method 2:

$getCategories = Category::paginate($limit);

Place the following code below the table component

{{ $getCategories->links() }}

Check the detailed documentation about Laravel Pagination

it's simple

---------use this in your controller---------
$categories = DB::table('category')
->paginate(3);

 return view('your_view_here',[
'categories' => $categories,
]);


-----------in your views file----------

@foreach($categories as $category)

{{$category-id}}

@endforeach

  <span>{{ $categories->appends(request()->input())->links() }}</span>

the span code is the paginate buttons

hope it will help u

Related