Try just doing this in the query
$comments = Comment::where('item_id' , '=' , $item)
->with('author:name')
->get();
If you want complete control I suggest using api resources (the nest perfectly)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
At the API endpoint i am trying to only return certain fields to the array, unfortunatly i cannot fathom how to bring back only certain fields in a nested data and can only seem to bring back all.
Here is the data im bringing back
id: example
title:example
comment:example
created_at: example
updated_at: example
author:[
id: example
name: example
email: example
]
Here is my controller:
$item = Item::where('slug', '=', $slug)->pluck('id');
$comments = Comment::where('item_id' , '=' , $item)
->with('author')
->get();
$subQuery = $comments->map(function ($comment) {
return collect($comment->toArray())
->only(['id', 'title', 'comment', 'created_at', 'updated_at', 'ratings', 'author'])
->all();
});
return response()->json($subQuery);
I only want to bring back the name from the author nest not all data, how do i do this?
But you can also just nest your own logic
$subQuery = $comments->map(function ($comment) {
$item = collect($comment->toArray())
->only(['id', 'title', 'comment', 'created_at', 'updated_at', 'ratings', 'author'])
->all();
$item['author'] = collect($item['author'])->only(['name'])->all();
return $item;
});
Please or to participate in this conversation.