Model collections #46666
Unanswered
CodeTechNL
asked this question in
Ideas
Model collections
#46666
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi! Lets say you have multiple product variants in a model called
Variant
. When retrieving a bunch of them$variants = Variant::all()
will return a (without autocomplete in my head) \Illuminate\Database\Eloquent\Collection. If we want to sum the total stock of those items we can use$variants->sum('stock_level')
. What I always do for each model, I override thenewCollection
method and return a specific collection for those models:VariantCollection
. So now when I retrieve my variants, I can use a method$variants->getStockLevel()
. Example code:Isn't the following method not much easier and cleaner?
With this method you don't need to override the whole method
Beta Was this translation helpful? Give feedback.
All reactions