0

I have a model for a collection which contains assets.

I wish to return the asset count with the collection resource though as a result this causes the whenLoaded function to be called which as a result loads all of the assets within the collection. I do not wish for this to occur.

I'm not sure how to go about creating a work around which will continue to allow me to use the resource, count the assets, but not call the whenLoaded function.

return [
        'id' => $this->id,
        'name' => $this->name,
        'description' => $this->description,
        'enabled' => $this->enabled,
        'sticky' => $this->sticky,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'asset_count' => $this->assets->where('enabled', 1)->count(),
        'assets' => Asset::collection($this->whenLoaded('assets')),
 ];

Is there a way to still use the resource, return the asset count, but not have the whenLoaded called as a result?

Aontaigh
  • 178
  • 1
  • 3
  • 13
  • Could you try `$this->assets()->where('enabled', 1)->count()`, it shouldn't load the relation this way – Remul Oct 04 '19 at 08:58

1 Answers1

4

Try this

you can simply create a new relationship like liveassets

function liveassets(){
 return $this->hasMany('assets')->where('enabled','=', 1);
}

return [
    'id' => $this->id,
    'name' => $this->name,
    'description' => $this->description,
    'enabled' => $this->enabled,
    'sticky' => $this->sticky,
    'created_at' => $this->created_at,
    'updated_at' => $this->updated_at,
    'asset_count' => $this->liveassets->count(),
    'assets' => $this->liveassets,
];
phpdroid
  • 1,642
  • 1
  • 18
  • 36
  • This will result in an [N+1 queries problem](https://stackoverflow.com/a/97253/9111901). Instead, you should use `'assets' => $this->whenLoaded('liveassets')` and use `->with('liveassets')` when passing the model(s) to the resource. There's also [`whenCounted`](https://laravel.com/docs/10.x/eloquent-resources#conditional-relationship-counts) for counting relationships. – jxxe Jul 07 '23 at 19:57