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.