Laravel 5.5 API Resources for Collections (Offline Data)

I was wondering if it is possible to define different data for a resource resource and a collection resource.

For the collection I want to send ['id', 'title', 'slug'] , but the resource of the element will contain additional information ['id', 'title', 'slug', 'user', etc.]

I want to achieve something like:

 class PageResource extends Resource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'slug' => $this->slug, 'user' => [ 'id' => $this->user->id, 'name' => $this->user->name, 'email' => $this->user->email, ], ]; } } class PageResourceCollection extends ResourceCollection { /** * Transform the resource collection into an array. * * @param \Illuminate\Http\Request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'slug' => $this->slug, ]; } } 

PageResourceCollection will not work properly because it uses PageResource , so it needs

 return [ 'data' => $this->collection, ]; 

I could duplicate the resource in PageFullResource / PageListResource and PageFullResourceCollection / PageListResourceCollection , but I'm trying to find a better way to achieve the same result.

+5
source share
2 answers

The Resource class has a collection method. You can return this as a parameter entered in your ResourceCollection, and then specify your transformations in the collection.

Controller:

 class PageController extends Controller { public function index() { return new PageResourceCollection(PageResource::collection(Page::all())); } public function show(Page $page) { return new PageResource($page); } } 

Resources

 class PageResource extends Resource { public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'slug' => $this->slug, 'user' => [ 'id' => $this->user->id, 'name' => $this->user->name, 'email' => $this->user->email, ], ]; } } class PageResourceCollection extends ResourceCollection { public function toArray($request) { return [ 'data' => $this->collection->transform(function($page){ return [ 'id' => $page->id, 'title' => $page->title, 'slug' => $page->slug, ]; }), ]; } } 
+6
source

The accepted answer works if you are not interested in links and metadata. If you want, just return:

 return new PageResourceCollection(Page::paginate(10)); 

in your controller. You should also look at loading other dependent dependencies before moving on to a collection of resources.

0
source

Source: https://habr.com/ru/post/1272071/


All Articles