API资源上的Laravel集合分页问题

如果我使用Laravel的分页方法,则下面的代码会给出Uncaught ErrorException: Trying to get property 'id' of non-object in...错误。如果我使用all(),效果很好。

 $articles = Models\Article::paginate(); // Eloquent collection
 return Article::collection(collect($articles));

Article.php

class Notification extends JsonResource
{
        public function toArray($request)
        {
            return [
                'id'      => $this->resource->id,'title'   => $this->resource->title,];
        }
    }

我也尝试过通过创建ResourceCollection并将查询结果发送给它,但这是相同的。

Collection {#547
  #items: array:12 [
    "current_page" => 1
    "data" => array:1 [
      0 => array:10 [
        "id" => 1
        "title" => "Test"
        "body"" => "test"
      ]
    ]
    "first_page_url" => "https://localhost/api/v1/articles?page=1"
    "from" => 1
    "last_page" => 1
    "last_page_url" => "https://localhost/api/v1/articles?page=1"
    "next_page_url" => null
    "path" => "https://localhost/api/v1/articles"
    "per_page" => 15
    "prev_page_url" => null
    "to" => 1
    "total" => 1
  ]
}

为什么它返回页码而不是完整对象?我想念什么?我检查了documentation,但当我使用分页时似乎由Laravel处理了。

ieboy2001 回答:API资源上的Laravel集合分页问题

我知道了。不需要使用collect帮助程序来包装查询结果。现在可以使用了。

本文链接:https://www.f2er.com/3117138.html

大家都在问