phplaraveleloquentlaravel-6laravel-eloquent-resource

What is the difference between a json resource & resource collection? in Laravel


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 App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class ShopCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

vs ...

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Shop extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

Solution

  • When you are converting a single model to json, that is a json resource, when you are converting a collection of model to json, that is resource collection.

    simply If you are returning a collection of resources or a paginated response that is a collection.

    See documentation

    to generating resources that transform individual models, you may generate resources that are responsible for transforming collections of models. This allows your response to include links and other meta information that is relevant to an entire collection of a given resource.