简体   繁体   中英

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

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($foo['something']);
})
->values();

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

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

You can use the transform method of laravel collections.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM