0
votes

I'm trying to filter the relationship models after they are loaded. This is an API and I want to return the model with fewer values. Simple example:

public function info(Post $post): Post {
    $post = $post->loadMissing(['responses']);
    $post->responses = $post->responses->filter(fn($res) => res->approved);
    return $post;
}

I don't want to filter the post responses on the query.

The line $post->responses = $post->responses->filter(fn($res) => res->approved); creates the attribute responses in the model, and does not change the value in the relations.

I've seen that when a Model is serialized the loaded relations are appended, so it overrides the attribute.

What is the best way to handle this?