Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel JsonResource (resource collection) add extra data to response

I’m working with laravel (v7) resources and I have a resource that extends JsonResource and I call this resource from the controller with pagination. I would like to add additional attribute extra next to the data array as follow:

{
    "data": [
    ],
    "links": {
    },
    "meta": {
    },
    "extra": {
        ....
    }
}

The problem with JsonResource is that they don’t work with with method. I tried to add the following to my resource collection but it did not make any difference.

    public function with($request)
    {
        return [
            'extra' => [
                'key' => 'value',
            ],
        ];
    }

The only way so far I found that works is when additional() method is called from within the controller chained to the resource itself like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

return (new UserCollection(User::all()->load('roles')))
                ->additional(['extra' => [
                    'key' => 'value',
                ]]);

But I want to add some data from the resource itself and this extra data is not available in the controller. Is there anyway to do this?

Edit:
Here is my Resource collection

class UserCollection extends JsonResource
{

    protected $result = [];


    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $this->result = [
            
            "attributes" =>[
                 "id"                   => $this->id,
                'name'                  => $this->name,
                'position'              => $this->position,
            ],
        ] ;

        return $this->result;
    }


    public function with($request)
    {
        return [
            'extra' => [
                'key' => 'value',
            ],
        ];
    }

}

And this is how it is called from the controller

$users = User::where('is_available', 1)->get();

$users = $users->paginate();    

return UserCollection::collection($users);

>Solution :

create JsonResource and ResourceCollection in two files by running php artisan make:resource user and php artisan make:resource userCollection.

You will have two separate files in same folder, user.php and userCollection.php.

use user.php which is JsonResource to customize your attributes and use userCollection.php

for reference https://laravel.com/docs/9.x/eloquent-resources#resource-collections

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading