laravel 如何在laravel api中使用分页?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41119579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:54:58  来源:igfitidea点击:

How to use pagination in laravel api?

phplaravelpagination

提问by Sayantan Das

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

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

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: $groupshas values returned from model. And if I dd($cursor);, I get

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

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 $datais blank.

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

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

What am I missing here?

我在这里错过了什么?

回答by Sagar Rabadiya

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

使用 fractal 的分页器实例格式化分页集合无需使用光标 下面是他们网站上的示例

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/

见这里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

或者使用 laravel-fractal 一个方便的包,它支持各种分页和一切。 https://github.com/spatie/laravel-fractal