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

2

12

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);
    }
}
Lillith answered 10/10, 2019 at 4:14 Comment(0)
T
10

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.

Tipster answered 10/10, 2019 at 6:12 Comment(1)
@MiguelStevens if you want to make some modifications based on request parameter, you can use that, if you would like to know more, go through my questions, I have posted a code regarding resource with query parameters.Tipster
G
2

Laravel Resource will transform and format your data before sending it to the client. (Single record)

Laravel Collection also does the same, but it holds multiple data records instead of a single record, and also, with the collection, we have access to functions like map, filter, and pluck to manipulate data

  • UserDetailsResource::make($user); (Single esource)
  • new UserResource($user); (Single resource)
  • UserDetailsResource::collection($users); => If collection

Note: In the latest PHP, we can add a return type to the function ex destroy(): void; if you use UserDetailsResource::collection($users); the return type will be :AnonymousResourceCollection. else :UserDetailsResource

Gasket answered 1/3, 2023 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.