Home > database >  How to get rid of unnecessary field (relation) from collection of Eloquent models?
How to get rid of unnecessary field (relation) from collection of Eloquent models?

Time:10-06

I've fetched bunch of models ::with('something'). I have a collection of these models with eager loaded collection. I've performed some operation on this collection and now I don't need this relation in my final JSON output.

How can I get rid of it?

return Foo::with(['something'])->get(['id', 'content', 'target']);

When I return JSON response I get 4 columns (id, content, target and something). I want 3 columns. How to get rid of something before the final return of response?

Which method should I use?

#relations: array:1 [
   "something" => Illuminate\Database\Eloquent\Collection {#1225

EDIT:

->each(function (Foo $foo) {
   unset($popup['something']);
})
->values();

This does the job but it doesn't look nice. Is there a better way?

CodePudding user response:

You can map (each accessor) the content and hide the relation:

return Foo::with(['something'])
    ->get(['id', 'content', 'target'])
    ->each->makeHidden('something');

Your method might work, but IMO it's not the best option, because if you (for example, in the future) will change the code, and manipulate the relation after the unset, then you might encounter some troubles, where instead hide is just "hiding" the relation (you can do the same with attributes) from the serialization

You can find the documentation here
If it's not clear why and how ->each->... works, check here

CodePudding user response:

You can use the transform method of laravel collections.

return Foo::with(['something'])->get()->transform(function($item, $key){
      return $item->only(['id', 'content', 'target']);
    });
  • Related