Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dionarap's avatar

Returning only certain nested API fields

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?

0 likes
9 replies
dionarap's avatar

@sinnbeck that doesn't work unfortunately, is eloquent resources the only way forward. Can nested values not be selected individually similar to the way im bringing back the array?

Sinnbeck's avatar

How is it not working? The : means it only selects the name from the database

Another idea is to use hide fields inside a map function like this

return $author->makeHidden('attribute')
dionarap's avatar

I can't get Author as suggested like that as it is nested. That seems to be the problem in the orginal code where i call 'author' it returns all of the author fields where as i only want to return the name in the author nest aswell as the rest of the data not in the author nest.

Sinnbeck's avatar

Can you try and run this and post the output?

$test = Comment::where('item_id' , '=' , $item)
        ->with('author:name')
        ->get();

dd($test->toArray());
Sinnbeck's avatar

What if you do this and set id as hidden on the model?



>with('author:id,name')
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

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;
    });
dionarap's avatar

Cheers man that works great, i understand what you're saying there.

Please or to participate in this conversation.