Additional data in Laravel Resource

Deadly 提交于 2021-02-10 18:23:40

问题


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

        ];
    }


回答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.



来源:https://stackoverflow.com/questions/59438633/additional-data-in-laravel-resource

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!