Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use pagination in laravel api?

My problem: I need to use pagination in the simple api that I am trying to develop using laravel. I was using Cursors to do it. But results are blank even if my model is returning result.

My code:

$newCursor = $groups->last()->id;
$cursor = new Cursor($cursor, $previousCursor, $newCursor, $groups->count());

//dd($cursor);

$groups =  new Collection(fractal($groups, new GroupRequestTransformer('filtered')));
$groups->setCursor($cursor);

$data = [
    'groups' => $groups,
    'cursor' => $cursor
 ];

$this->setResponseStatus(true, 200, trans('group.filtered'));
return $this->sendResponseData($data);

Note: $groups has values returned from model. And if I dd($cursor);, I get

Cursor {#403
  #current: "5"
  #prev: null
  #next: 13
  #count: 1
}

so this seems fine to. But the the actual response that I am sending as $data is blank.

"data": {
    "groups": {},
    "cursor": {}
  }

What am I missing here?

like image 654
Sayantan Das Avatar asked Nov 09 '22 04:11

Sayantan Das


1 Answers

use fractal's paginator instance to format the paginated collection no need to use cursor below is the example on their site

use League\Fractal\Resource\Collection;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Acme\Model\Book;
use Acme\Transformer\BookTransformer;

$paginator = Book::paginate();
$books = $paginator->getCollection();

$resource = new Collection($books, new BookTransformer);
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));

see here http://fractal.thephpleague.com/pagination/

or use laravel-fractal a handy package which has support for all kind of pagination and everything. https://github.com/spatie/laravel-fractal

like image 175
Sagar Rabadiya Avatar answered Nov 14 '22 22:11

Sagar Rabadiya