Can someone explain the difference between a ResourceCollection and JsonResource?
In Laravel 6 docs you can generate 2 different types of resources… ResourceCollection and JsonResource. https://laravel.com/docs/6.x/eloquent-resources#resource-responses
<?php
namespace AppHttpResources;
use IlluminateHttpResourcesJsonResourceCollection;
class ShopCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param IlluminateHttpRequest $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
vs …
<?php
namespace AppHttpResources;
use IlluminateHttpResourcesJsonJsonResource;
class Shop extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param IlluminateHttpRequest $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
Advertisement
Answer
ResourceCollection
use for a list of items but JsonResource
use for a single item.
I copy piece of code that used it in my project:
in my project I had list of articles, so I have to showed list of articles, so I used ResourceCollection
that return a array of articles :
<?php
namespace AppHttpResourcesApiCollection;
use IlluminateHttpResourcesJsonResourceCollection;
class AlbumCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param IlluminateHttpRequest $request
* @return array
*/
public function toArray($request)
{
return $this->collection->map(function ($item) {
return [
'id' => $item->id,
'name' => $item->name,
'description' => $item->description
];
});
}
public function with($request)
{
return [
'status' => true
];
}
}
this code return for I a list of articles. then when user click on a article, I must show to user a single article, so I must return a single article and I used following code:
<?php
namespace AppHttpResourcesApiResources;
use IlluminateHttpResourcesJsonJsonResource;
class NewsResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param IlluminateHttpRequest $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
'cover' => $this->cover,
'view_count' => $this->view_count,
'comment_count' => $this->comment_count,
'like_count' => $this->like_count,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'comments' => $this->comments
];
}
public function with($request)
{
return [
'status' => true
];
}
}
you can see the this my answer that related to your question
I hope you find it useful.