Home > Net >  Laravel JsonResource (resource collection) add extra data to response
Laravel JsonResource (resource collection) add extra data to response

Time:04-07

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:

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);

CodePudding user response:

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

  • Related