Skip to content

Broken BelongsToMany type definitions #55078

Closed
@amants

Description

@amants

Laravel Version

12.3

PHP Version

8.4

Database Driver & Version

No response

Description

Ever since the last update, all of the many to many relations in my project have broken linting definitions.

Original code:

    /**
     * @return BelongsToMany<Role, $this>
     */
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'user_role');
    }

Linting error:

Method App\Domain\User\Models\User::roles() should return Illuminate\Database\Eloquent\Relations\BelongsToMany<App\Domain\Role\Models\Role, $this(App\Domain\User\Models\User)> but returns  
         Illuminate\Database\Eloquent\Relations\BelongsToMany<App\Domain\Role\Models\Role, $this(App\Domain\User\Models\User), Illuminate\Database\Eloquent\Relations\Pivot>.                         
         🪪  return.type  

When adding Pivot to the PHPDoc:

    /**
     * @return BelongsToMany<Role, $this, Illuminate\Database\Eloquent\Relations\Pivot>
     */
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'user_role');
    }

Linting error:

Generic type Illuminate\Database\Eloquent\Relations\BelongsToMany<App\Domain\Role\Models\Role, $this(App\Domain\User\Models\User), Illuminate\Database\Eloquent\Relations\Pivot> in PHPDoc tag @return specifies 3 template types, but  
         class Illuminate\Database\Eloquent\Relations\BelongsToMany supports only 2: TRelatedModel, TDeclaringModel    

Steps To Reproduce

Create a model with a many-to-many relationship.

Declare the phpdoc like:

    /**
     * @return BelongsToMany<Role, $this>
     */

Run phpstan with level 9.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions