Salvis's avatar
Level 14

PHPStan and Custom Query Builder

Hi Laravel and PHPStan experts. Is it somehow possible to make PHPStan recognise usage of $this keyword that is referencing a Model instance from within a Custom Query Builder? Please see the illustration below. Thanks!


use Illuminate\Database\Eloquent\Model;

class WorkOrder extends Model
{
    // ...

    public function assignments()
    {
         return $this->hasMany(Assignment::class);
    }

    public function newEloquentBuilder($query): WorkOrderBuilder
    {
         return new WorkOrderBuilder($query);
    }

    // ...
}

use Illuminate\Database\Eloquent\Builder;

class WorkOrderBuilder extends Builder
{
    public function getActiveAssignment()
	{
        $this->assignments // PHPStan goes mad
    }
}

0 likes
1 reply
Salvis's avatar
Level 14

Sorry LaryAI for accidentally removing your replay - your answer was correct.

In the WorkOrderBuilder class, the @mixin PHPDoc annotation should be added to tell PHPStan that methods from the WorkOrder model can be called on $this.


/**
 * @mixin WorkOrder
 */
class WorkOrderBuilder extends Builder
{
    public function getActiveAssignment()
	{
        $this->assignments; // PHPStan is happy
    }
}

Please or to participate in this conversation.