Search code examples
phplaravellaravel-5eloquentlaravel-resource

Retrieving eloquent api resource using keyby collection method


I have an end API point

users/{user}

now in User resource, I want to return

     public function toArray($request)
        {
            // return parent::toArray($request);

            return [
                'id' => $this->id,
                'name' => $this->name,
//                'comments' => $this->post->comments->keyBy('post_id')
                'comments' => new CommentCollection($this->post->comments->keyBy->post_id)

            ];
        }

CommentCollection class

public function toArray($request)
    {
        // return parent::toArray($request);

        return [
            'data' => $this->collection->transform(function($comment){
                return [
                    'id' => $comment->id,
                    'comment' => $comment->comment,
                ];
            }),
        ];
    }

but the result will not include the post_id as key, how I can make it return the comments collection having key post_id?

Update

use App\models\Post;
use App\Http\Resources\Postas PostResource;

Route::get('/posts', function () {
    return PostResource::collection(Post::all()->keyBy->slug);
});

This is working correctly, but if I will use post collection inside User resource as relationship, it is not working! and that is my requirement in comments collection.


Solution

  • What I did it, I created another ResourceGroupCollection class

    <?php
    namespace App\Http\Resources\Collection;
    
    use Illuminate\Http\Resources\Json\ResourceCollection;
    
    class CommentGroupCollection extends ResourceCollection
    {
        public $collects = 'App\Http\Resources\Collection\CommentCollection';
    
        public $preserveKeys = true;
    
        public function toArray($request)
        {
            return $this->collection;
        }
    
    }
    
    <?php
    namespace App\Http\Resources\Collection;
    
    use Illuminate\Http\Resources\Json\ResourceCollection;
    
    class CommentCollection extends ResourceCollection
    {
        public $collects = 'App\Http\Resources\Comment';
    
        public $preserveKeys = true;
    
        public function toArray($request)
        {
            return $this->collection;
        }
    
    }
    
    and then 
    
    new CommentGroupCollection($comments->groupBy('post_id')),