From 0b4ef6d5d373c39a0fd5b9f9f845fea07a490e7d Mon Sep 17 00:00:00 2001 From: Andrew Brown Date: Fri, 12 Dec 2025 14:33:55 -0600 Subject: [PATCH] update documentation for custom collections there are 3 ways to define a custom collection, 2 of which are currently documented - `CollectedBy` attribute - override `newCollection()` method - override `$collectionClass` property (undocumented) surprisingly, the undocumented option is arguably the best. it doesn't have the performance hit from Reflection of the attribute, and doesn't force the complete override of a parent method which may miss out on upstream changes. I went aggressive in this commit, and removed the 2 current options in favor of the single best one. However, I could see the argument to keep the "attribute" option, and would add that back in if desired. --- eloquent-collections.md | 40 ++++++---------------------------------- 1 file changed, 6 insertions(+), 34 deletions(-) diff --git a/eloquent-collections.md b/eloquent-collections.md index 21d08dae2f..37c6e184c3 100644 --- a/eloquent-collections.md +++ b/eloquent-collections.md @@ -316,25 +316,7 @@ $users = $users->withoutAppends(); ## Custom Collections -If you would like to use a custom `Collection` object when interacting with a given model, you may add the `CollectedBy` attribute to your model: - -```php - $models - * @return \Illuminate\Database\Eloquent\Collection + * @var class-string<\Illuminate\Database\Eloquent\Collection<*, *>> */ - public function newCollection(array $models = []): Collection - { - $collection = new UserCollection($models); - - if (Model::isAutomaticallyEagerLoadingRelationships()) { - $collection->withRelationshipAutoloading(); - } - - return $collection; - } + protected static string $collectionClass = UserCollection::class; } ``` -Once you have defined a `newCollection` method or added the `CollectedBy` attribute to your model, you will receive an instance of your custom collection anytime Eloquent would normally return an `Illuminate\Database\Eloquent\Collection` instance. +Once you have defined the `$collectionClass` property on your model, you will receive an instance of your custom collection anytime Eloquent would normally return an `Illuminate\Database\Eloquent\Collection` instance. -If you would like to use a custom collection for every model in your application, you should define the `newCollection` method on a base model class that is extended by all of your application's models. +If you would like to use a custom collection for every model in your application, you should define the `$collectionClass` property on a base model class that is extended by all of your application's models.