3

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

        ];
    }

Peter
  • 655
  • 1
  • 14
  • 37

1 Answers1

1

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.

Bostjan
  • 774
  • 6
  • 11
  • how is that additional data going to be available to the Resource, as it is set on the Collection? – lagbox Dec 21 '19 at 22:25
  • https://laravel.com/docs/master/eloquent-resources#adding-meta-data check under "Adding Meta Data When Constructing Resources" In returned json the main collection will be available as "data" and some_id will be available as ->some_id – Bostjan Dec 21 '19 at 22:28
  • on the collection, not the individual resources, their `toArray` method is on the Resource not the Collection ... I am trying to find where the Collection which will end up calling `toArray` on each resource would be passing this additional data to it – lagbox Dec 21 '19 at 22:28
  • I found a solution: I'm passing the `id` as session variable to the ProjectResource. It's not the best way i think, but it works. – Peter Dec 24 '19 at 09:50