HasMany Relations break when using custom collections
Laravel Version
11.28.1
PHP Version
8.3.12
Database Driver & Version
PgSQL
Description
When using a custom collection on an eloquent model as suggested in the docs here, if that model is referenced as a hasMany by other models, it throws a TypeError because Illuminate\Database\Eloquent\Relations\HasMany::match(): Argument 2 ($results) must be of type Illuminate\Database\Eloquent\Collection, App\Collections\PostCollection given
Steps To Reproduce
#[CollectedBy(PostCollection::class)]
final class Post extends Model
{
}
final class User extends Model
{
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
}
$user = \App\Models\User::query()->with(['posts'])->first();
Hey there, thanks for reporting this issue.
We'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue as one separate commit on the main/master branch and share the repository here?
Please make sure that you have the latest version of the Laravel installer in order to run this command. Please also make sure you have both Git & the GitHub CLI tool properly set up.
laravel new bug-report --github="--public"
Do not amend and create a separate commit with your custom changes. After you've posted the repository, we'll try to reproduce the issue.
Thanks!
Make sure your App\Collections\PostCollection extends Illuminate\Database\Eloquent\Collection
Thanks, i was using an Illuminate\Support\Collection. Changed to Illuminate\Database\Eloquent\Collection and work.