Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kiwi0134's avatar

Using DocBlocks with Generics for Custom Collections

Hello,

I have a custom collection for a model, like a UserCollection with special abilities. Laravel uses the standard @template tag to make the IDE and Code Analysers aware of the generic ability of the Collection class.

My UserCollection extends the Collection class. How can I use the docblocks to tell PHPStorm, that the TValue inside the Collection is always a User model? I found the following resources, but I don't quite understand what I have to do to achieve this:

I've tried the following, but PHPStorm still cannot resolve the type of $this->each:

/**
 * @extends \Illuminate\Support\Collection<int, \App\Models\User>
 */
class UserCollection extends Collection
{
    public function reserve()
    {
        return $this->each->doSomething();
    }
}
0 likes
4 replies
LaryAI's avatar
Level 58

To specify that the TValue inside the Collection is always a User model, you can use the @template tag in the docblock of your UserCollection class. Here's an example:

/**
 * @template TValue of \App\Models\User
 * @extends \Illuminate\Support\Collection<int, TValue>
 */
class UserCollection extends \Illuminate\Support\Collection
{
    public function reserve()
    {
        return $this->each->doSomething();
    }
}

In this example, we're using the @template tag to define a type parameter TValue that extends \App\Models\User. We're then using TValue as the type parameter for the parent Collection class.

With this docblock, PHPStorm should be able to resolve the type of $this->each as \App\Models\User.

kiwi0134's avatar

@LaryAI This, unfortunately doesn't work. each is still of type HigherOrderCollectionProxy with TValue being not defined.

aschmelyun's avatar

@kiwi0134 I know it's a bit late, but one of these two PHPDocs should work for your case. They helped fix this issue with my custom Collection class:

/**
 * @property \Illuminate\Support\Collection<\App\Models\User> $each
 * @method \Illuminate\Support\Collection<\App\Models\User> each()
 */
class UserCollection extends Collection
{
    public function reserve()
    {
        return $this->each->doSomething();
    }
}
1 like
piotrzatorski's avatar

You can also use this, which will give you better PHPStorm autocomplete for every method in Collection

/**
 * @template-extends Collection<int, \App\Models\User>
 */
1 like

Please or to participate in this conversation.