-
Notifications
You must be signed in to change notification settings - Fork 11.1k
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
[8.x] Preserve eloquent collection type after calling ->fresh() #34848
[8.x] Preserve eloquent collection type after calling ->fresh() #34848
Conversation
Why don't we just fix map? |
Ok, two points: A) B) The bug is actually more nuanced than I originally thought (will update the description to reflect shortly):
However, if a model inside a model collection doesn't exist in the database, Example: $models = User::all();
$models->add(new User); // Or $models->first()->delete();
$models->fresh(); // Does NOT return a model collection The reason is because of this line in the return $this->map(function ($model) use ($freshModels) {
return $model->exists && isset($freshModels[$model->getKey()])
? $freshModels[$model->getKey()] : null;
}); Notice that if any model in the collection does not exist in the database, the map will return Because the collection now contains a So ultimately the question is: How do you expect My expectation would be that it would strip out models that don't exist and still return a model collection. If we consider filtering out nulls from the result of ->fresh a breaking change, I would say, merge this PR, then write a new one for the |
Ping @JosephSilber ... curious your thoughts. |
|
Thanks for the feedback @JosephSilber |
@calebporzio I kinda think we should just remove the |
This PR fixes unexpected behavior of an Eloquent collection's
->fresh()
method.Current Behavior:
New Behavior:
Cause of bug:
Calling
->fresh()
will not remove non-existent models, it will set them to null.Now that the collection contains null values,
->fresh()
's internal->map
call will detect that the collection contains non-model values and return a "Illuminate\Support\Collection" instead.Current Proposed Solution:
->map
call in anew static
to ensure that the class matches the original eloquent collection type (will even support custom eloquent collections this way).Ideal Solution: (But potentially breaking)
->fresh()
on a model collection, REMOVE the items that are not in the database completely (instead of replacing them with null values)Why I Care:
Livewire supports setting public properties as eloquent collections.
If a developer deletes one of the items in the collection and then calls
->fresh()
, because the collection will now be a normal collection and not a model one, Livewire will not recognize it and will break.I'm happy to PR the "Ideal" solution if it can be merged to 8.x.
Thanks!