In Laravel API Resources to hide fields in the output in the collection?

There is, for example, route to output a list of articles, and route to output a specific article:
public function index()
{
 return new ArticleCollection(Article::all());
}

public function show(Article $article)
{
 return new ArticleResource($article);
}


In ArticleResource:
public function toArray($request)
{
 return [
 'id' => $this->id,
 'title' => $this->title,
 'content' => $this->content,
];
}


In ArticleCollection:
public function toArray($request)
{
 return [
ArticleResource::collection($this->collection),
];
}


Is it possible to make it so that when you output the list of articles not displayed in content field, not creating even one additional ArticleResource separately to list?

I.e. roughly speaking for the first routes to get the json:
{
 "data": [
{
 "id": 1,
 "title": "Title 1"
},
{
 "id": 2,
 "title": "Title 2"
}
]
}


For a second get to:
{
 "data": {
 "id": 1,
 "title": "Title 1",
 "content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
}
}


May be using $this->when to check that it displays the resource within a collection or something?
March 19th 20 at 08:35
3 answers
March 19th 20 at 08:37
Solution
Found here is the solution. Maybe not super convenient, but solves my problem.
From the resource collection you can pass a flag in the resource model - efrain_Pur commented on March 19th 20 at 08:40
March 19th 20 at 08:39
public function toArray($request)
{
 return $this->collection
->map
 ->toArray($request, true)
->all();
 }


public function toArray($request, $isCollection = false)
Thanks, good idea - jan commented on March 19th 20 at 08:42
March 19th 20 at 08:41
Why select(id, title) does not specify only what you need, why bother with a database to pull out all, which would then hide?
Because when fields are much, much easier to specify which fields I would like to hide, than to list all that you want to show.
And once in the Resource file and so we enumerated all of them, the duplication of the field list in the controller, will complicate future work. You will need to add a field to output, in addition to the Resource file, you will need to select search all s and add more fields there. - jan commented on March 19th 20 at 08:44
I agree with that, but this solution is suitable for simple systems.

Extra data is traffic and traffic is money and speed. On Amazon traffic is quite expensive.

If ignore field is always different, it's best to make your scope in which you want to specify the fields to ignore, as a basis for taking fillable - constantin83 commented on March 19th 20 at 08:47
Yes, about the scope good idea. Thank you. - jan commented on March 19th 20 at 08:50

Find more questions by tags LaravelAPI