0

I got a little issue to solve. In my app I am handling with a lot of Models and each model does have something like:

  • ModelResource
  • ModelResourceCollection
  • ModelResourceOverview
  • ModelResourceOverviewCollection

The reason is: Sometimes I don't need all the information that are visible if I am using the ModelResource - in this case I am calling the ModelResourceOverview.

Example

PostResource

- title
- tags
- content
- author

Example

PostOverviewResource

- title
- author

As I have a lot of Models I have a huge number of ApiResource-Classes and I want to get rid of that.

I thought about using $this->when in the Resource and pass something like "full" or "overview" to the request in the Controller.

Example

$data
    = new PostResource($this->post);

So my question is: Is it the best way to add this to the request or is there a handier/nicer way to handle this?

SPQRInc
  • 162
  • 4
  • 23
  • 64

2 Answers2

0

Laravel has a way to hide fields on the fly: Hiding attributes from json

e.g.

return $post->makeHidden('content')->toArray();
coedycode
  • 380
  • 1
  • 8
0

If your logic about "visible or not" is bound to the current request, then you should use when or mergeWhen as you mentioned (everything here https://laravel.com/docs/7.x/eloquent-resources#conditional-attributes ), therefore you'll only have 2 resources instead of 4

public function toArray($request)
{
    return [
        'title' => $this->title,
        'author' => $this->author,
        $this->mergeWhen($this->needsFullData($request), [
            'tags' => $this->tags,
            'content' => $this->content,
        ]),
    ];
}

protected function needsFullData($request)
{
    //Your logic
}
Shizzen83
  • 3,325
  • 3
  • 12
  • 32