【问题标题】:Laravel Collection Pagination Problem on API ResourceAPI 资源上的 Laravel 集合分页问题
【发布时间】:2019-11-12 13:15:00
【问题描述】:

如果我使用 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 处理的。

【问题讨论】:

    标签: php laravel collections eloquent pagination


    【解决方案1】:

    我想通了。没有必要用 collect 助手包装查询结果。现在可以了。

    【讨论】:

      猜你喜欢
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 2022-07-26
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 2019-09-09
      相关资源
      最近更新 更多