'Laravel add API Resources add attribut only when use collection
I want to add attribut to resource when we use collection !
PostResource :
public function toArray($request)
{
return [
'id' => $this->id,
'content' => $this->content,
'user' => new UserResource($this->whenLoaded('user')),
];
}
PostCollection :
public function toArray($request)
{
return [
'data' => $this->collection
];
}
in controller :
$posts = Post::with('user')->get();
return PostResource::collection($posts);
return
["data": { ["id":1 , "content" : "some test" , "users": [....] }]
we want to add another attribut (short_text)
["data": { ["id":1 , "content" : "some test" , "users": [....] , "short_text" : substr($this->content",0,255) }]
how to do it ?
we don't want to edit the PostResource because the short_text will be included on every request.
we wan't to include it when we use collection only !
so:
localhost/api/posts
return
["data": { ["id":1 , "content" : "some test" , "users": [....] , "short_text" : substr($this->content",0,255) }]
and
localhost/api/post/1
return :
["id":1 , "content" : "some test" , "users": [....] ]
without the short_text attribut
Solution 1:[1]
As stated in the docs, you could do this:
class PostCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection,
'short_text' => 'my-short-text',
];
}
}
Of course, you can shape it as you like to have the desired structure.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kenny Horna |
