flarum / flarum/framework

[2.x] Nested eager loading causes an undefined relationship error

Open
#5,042 1 comment 0 reactions 0 assignees View on GitHub
type/bug
Dominant language
PHP
Stars
6.7k
Forks
883
Avg merge
15h 16m
Merged PRs (30d)
73

Description

### Current Behavior

Initially reported here: https://discuss.flarum.org/d/5791-masquerade-by-friendsofflarum-the-user-profile-builder/230. I found that the issue is in Flarum core.

Using `eagerLoadWhere()` with a nested relationship can cause an API request to fail with:
```
Call to undefined relationship [user] on model [Flarum\User\User].
```

Moving the nested load into a `with()` callback inside `eagerLoadWhere('user', ...)` resolves the error.

### Steps to Reproduce

See this code: https://github.com/FriendsOfFlarum/masquerade/blob/40c4f6284c56810c6231b189e1e4c6bddd138d60/extend.php#L105-L107
Workaround: https://github.com/FriendsOfFlarum/masquerade/pull/120/changes

### Expected Behavior

Loading a nested relationship should not cause an undefined relationship error.

### Screenshots

_No response_

### Environment

- Flarum version: v2.0.0-rc.8

### Output of `php flarum info`

_No response_

### Possible Solution

_No response_

### Additional Context

AI-assisted analysis (GPT Astra-6):

The suspected cause is in `getWhereEagerLoadsFor()` in:

https://github.com/flarum/framework/blob/4686ef50940a3c7bfbfbe1151d3d9fcaf73dcb5b/framework/core/src/Api/Endpoint/Concerns/HasEagerLoading.php#L254

This keeps the full relationship path as the key and replaces the constraint callback with a string. EloquentBuffer passes the result to `with()` on the related model's query.

The suggested fix is to use the relative path as the key and preserve the callback, passing it the query and context. This core change has not been tested.

Contributor guide

Open the contributing guide

Research direction

Start at framework/core/src/Api/Endpoint/Concerns/HasEagerLoading.php and inspect getWhereEagerLoadsFor(), then compare the Masquerade extend.php example and workaround in pull request #120. Reproduce the nested eagerLoadWhere() request and verify the API no longer reports an undefined relationship on Flarum\User\User; the suggested core change is untested.

Written by the indexing model from the issue text.

Assessment

Tech stack
laravel, php
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
65/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.