Peter
Peter

Reputation: 771

Additional data in Laravel Resource

I use Laravel resource from the controller:

        $data = Project::limit(100)->get();

        return response()->json(ProjectResource::collection($data));

I like to pass additional information to the ProjectResource. How it's possible? And how can i access the additional data?

I tried like this:

        $data = Project::limit(100)->get();

        return response()->json(ProjectResource::collection($data)->additional(['some_id => 1']);

But it's not working.

What's the right way?

I like to access the some_id in the resource like this.

    public function toArray($request)
    {

        return [
            'user_id'                =>      $this->id,
            'full_name'              =>      $this->full_name,
            'project_id'             =>      $this->additional->some_id

        ];
    }

Upvotes: 5

Views: 21508

Answers (3)

Ahsaan Yousuf
Ahsaan Yousuf

Reputation: 715

This is what I had to do in Laravel v11. Instead of calling additional() method on AnonymousResourceCollection class which gets return on Resource's collection() method. We are iterating over items (actual resource class) and passing the data via additional method.

tap(ProjectResource::collection($data), function ($resource) {
    $resource->collection->map(fn (ProjectResource $item) => $item->additional([
        'foo' => 'bar'
    ]));
});

Upvotes: 0

Ihtisham Ul haq
Ihtisham Ul haq

Reputation: 1

$data = Project::limit(100)->get();

return $this->sendResponse(ProjectResource::collection($data), ['some_id' => 1]);`

You will receive the below json response:

{
  "success": true,
  "data": [
    {
        your $data
    }
  ],
  "message": {
      "some_id": 1,
  }
}

You can access some_id from the json.

Upvotes: -1

Bostjan
Bostjan

Reputation: 814

In your controller don't wrap return Resource in response()->json. Just return ProjectResource.

So like:

$data = Project::limit(100)->get();
return ProjectResource::collection($data)->additional(['some_id => 1']);

Sorry for misunderstanding the question. I don't think there is an option to pass additional data like this. So you will have to loop over the collection and add this somehow.

One option is to add to resources in AnonymousCollection. For example:

$projectResource = ProjectResource::collection($data);
$projectResource->map(function($i) { $i->some_id = 1; });
return $projectResource;

and then in ProjectResource:

return [
  'user_id' => $this->id,
  'full_name' => $this->full_name,
  'project_id' => $this->when( property_exists($this,'some_id'), function() { return $this->some_id; } ), 
];

Or add some_id to project collection befour passing it to ResourceCollection.

Upvotes: 3

Related Questions