Search code examples
jsonlaravelapicollectionsresponse

Retrieve only necessary data


Here is my store function

public function store(Request $request)
{
    $post = new Post();
    $post->author()->associate(auth()->user());
    $post->fill($request->all());
    $post->save();

    return response()->json($post);
}

As a response i get:

enter image description here

I don't want all the data so I tried to take only the data I have defined like this:

$post = $post->only([
    'id',
    'title',
    'content',
    'published_at',
    'author'
]);

And response now is:

enter image description here

Much better, but not completely. I can not define post author data in this way. The only way is by creating a creepy relationship where you select only necessary data or like this:

    $post = [
        'id' => $post->id,
        'title' => $post->title,
        'content' => $post->content,
        'published_at' => $post->published_at->toDateTimeString(),
        'author' => [
            'id' => $post->author->id,
            'name' => $post->author->name,
            'email' => $post->author->email,
        ]
    ];

So my question is... maybe there is more elegant way to achieve this.

Thank you very much!


Solution

  • The simplest way would probably be to just use only with the author as well:

    return $post->only('id', 'title', 'content') + [
            'author' => $post->author->only('id', 'name', 'email'),
        ];
    

    If it was going to get any more complicated or reused somewhere else then I would suggest using something like Eloquent Resources