如何在laravel api中使用分页?

Say*_*Das 5 php pagination laravel

我的问题:我需要在我尝试使用 laravel 开发的简单 api 中使用分页。我正在使用游标来做到这一点。但是即使我的模型正在返回结果,结果也是空白的。

我的代码:

$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);
Run Code Online (Sandbox Code Playgroud)

注意:$groups具有从模型返回的值。如果我dd($cursor);,我得到

Cursor {#403
  #current: "5"
  #prev: null
  #next: 13
  #count: 1
}
Run Code Online (Sandbox Code Playgroud)

所以这似乎很好。但是我发送的实际响应$data是空白的。

"data": {
    "groups": {},
    "cursor": {}
  }
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?

小智 1

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));
Run Code Online (Sandbox Code Playgroud)

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

或者使用 laravel-fractal 一个方便的包,它支持所有类型的分页和所有内容。 https://github.com/spatie/laravel-fractal