-
Notifications
You must be signed in to change notification settings - Fork 10.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Model's newCollection method runs twice #16174
Comments
Please could you provide a small code sample. Thanks. :) |
Here is my model, with the
Basically, I would like to alter the items of a collection in my models. |
This is expected behavior and doesn't have anything explicitly to do with the fact that you're overriding the method. When you call the In order for the builder to not call I'm a little fuzzy as to what you're trying to do as it really shouldn't matter that this is being called multiple times. The purpose of the method, as stated in the docs is to allow you to use a custom collection class over the Illuminate Collection class. It seems to me that attempting to modify the contents of the collection in this method is probably bad idea. Can you provide some more context as to what you're trying to do? It seems there is likely a better place for you to transform your collection than in this method. |
I wanted to add user related fields to the collection models. So adding fields to the post, like is the user marked that post as favorite or not, which data comes from not an exact relation. So when I used this, I realized it duplicate the queries. I had a workaround with adding another method, just tought it's the right way to modify collections |
Yeah, It seems that you could maybe use an attribute getter for something like that:
Then any model that you use in your blade files or whatever will check when you try to access the If you want that attribute to automatically be added to the model for json and array serialization ( like in an API response ), you can add it to the
|
Reference in the docs
Description:
When overriding base model with
newCollection
method, it runs twice.Database\Eloquent\Builder\get > getModels > hydrate > newCollection
Database\Eloquent\Builder\get > newCollection
Steps To Reproduce:
newCollection
method in a modelThe text was updated successfully, but these errors were encountered: