简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM