简体   繁体   中英

Laravel Collection Pagination Problem on API Resource

The code below gives Uncaught ErrorException: Trying to get property 'id' of non-object in... error if I use pagination method of Laravel. If I use all() , it works fine.

 $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,
            ];
        }
    }

I also tried by creating a ResourceCollection and send query result to it, but it was the same.

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
  ]
}

Why does it return the page number, instead of full object? What do I miss? I checked documentation but it seems like it is handled by Laravel when I use paginate.

I figured it out. Wrapping the query result with collect helper was unnecessary. It works now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM