with([...]) does not resolve the Relation closure parameter to the concrete relation, unlike with(..., $closure)
- Larastan Version: 3.12.0
- Laravel Version: 12.69.2
- PHPStan Version: 2.2.14
Description
with() resolves its Relation closure parameter to the concrete relation when the closure is the second argument. It does not when the closure sits inside the array. The receiver then stays the abstract Relation, so model scopes and SoftDeletes methods read as undefined.
This is the case #2053 reported. #2042 fixed the generic query-builder half, so where() and whereNull() resolve now. The array form still does not know which model it is looking at.
Reproducer
<?php declare(strict_types = 1);
namespace App;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
/** @return HasMany<Comment, $this> */
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
}
class Comment extends Model
{
use SoftDeletes;
/** @param Builder<Comment> $query */
public function scopeApproved(Builder $query): void
{
}
}
class Loader
{
public function direct(): void
{
Post::query()->with('comments', function (Relation $q): void {
\PHPStan\dumpType($q); // HasMany<App\Comment, App\Post>
$q->approved(); // ok
$q->withTrashed(); // ok
});
}
public function inArray(): void
{
Post::query()->with([
'comments' => function (Relation $q): void {
\PHPStan\dumpType($q); // Relation
$q->where('a', 1); // ok
$q->whereNull('b'); // ok
$q->approved(); // method.notFound
$q->withTrashed(); // method.notFound
},
]);
}
}Call to an undefined method Illuminate\Database\Eloquent\Relations\Relation::approved().
Call to an undefined method Illuminate\Database\Eloquent\Relations\Relation::withTrashed().
method.notFoundExpected
The array form resolves the same way the second-argument form does, so the dumped type is HasMany<App\Comment, App\Post> in both.
Note for anyone hitting this after a PHPStan upgrade
PHPStan 2.3.x infers closure parameter types inside array arguments, which the 2.2 line only did for a closure passed directly. The behaviour here does not change, but the reported receiver does, from Relation to Relation<*, *, *>. An ignoreErrors pattern written against the old text stops matching, so the errors look new. They are not.
Source: larastan/larastan