Skip to content

Conversation

@dokisof
Copy link
Contributor

@dokisof dokisof commented Oct 23, 2025

Laravel’s load() method passes a relationship instance (e.g., BelongsToMany, HasMany, etc.) to the callback, not a Builder.
As a result, using Builder $query causes a type error similar to:

Argument #1 ($query) must be of type Illuminate\Database\Eloquent\Builder, Illuminate\Database\Eloquent\Relations\BelongsToMany given

Argument laravel#1 ($query) must be of type Illuminate\Database\Eloquent\Builder, Illuminate\Database\Eloquent\Relations\BelongsToMany given

```php
$author->load(['books' => function (Builder $query) {
$author->load(['books' => function ($query) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not

Suggested change
$author->load(['books' => function ($query) {
$author->load(['books' => function (BelongsToMany $query) {

then?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option would be

Suggested change
$author->load(['books' => function ($query) {
$author->load(['books' => function (\Illuminate\Contracts\Database\Eloquent\Builder $query) {

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure about this, because the same callback pattern can be used for HasMany as well.
And while the 2nd suggestion removes the type error mentioned above, it breaks IDE autocompletion (Undefined method 'where').
What about \Illuminate\Database\Eloquent\Relations\Relation ?

Copy link
Contributor

@shaedrich shaedrich Oct 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, Relation works 👍🏻

@taylorotwell taylorotwell merged commit f371188 into laravel:12.x Oct 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants