Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

thefelipevega's avatar

Polymorphic Relationship Not Eager-Loading Correctly

We're currently in the process of trying to optimize some of our application's load times using eager-loading, however, we've run into an issue when trying to load relationships using the $with property and a custom method name.

In our application we have a concept of a Step that can be a Screen among other things, and can be tracked via a StepRecord model that relates the Step you came from and the Step you went to. The StepRecord tracks its relationships with a to and from method, as shown below with the to method.


class StepRecord extends SmartModel
{
    protected $with = ['to'];

    ...

    public function to()
    {
        return $this->morphTo('stepable_to');
    }
}

However, when we try to eager-load the to value, in this case the model morphed via a stepable_to column, Eloquent seems to bypass the function name and insert it directly as the column name into the relations array.

#relations: array:2 [
    "to" => null
    "stepable_to" => App\Models\Screen^ {#1666
      #guarded: []
      #connection: "sqlite"
      #table: "screens"
      #primaryKey: "id"
      ...
]

This, of course, causes our tests to break as $stepRecord->to is now null, even though it's being eager-loaded.

We can go back and refactor everything to be 1-1 naming wise, but this severely impacts the readability of the code and seems like something that should be accounted for by Eloquent.

Before I post this as a bug on the Laravel Framework repo, weve done research, tried different methods such as placing the with on the builder call and not as a property on the model, and even upgrade to 6.0 (we were on 5.7 before) but nothing has helped.

Does anyone have any ideas how to make it so that if I have a relationship-function that tracks a morph, when I eager-load said morph its passed into the relations array correctly? Is this even possible in Laravel right now?

0 likes
2 replies
staudenmeir's avatar
Level 24

That's a known issue. Use this definition instead:

public function to()
{
    return $this->morphTo(null, 'stepable_to_type', 'stepable_to_id');
}
7 likes

Please or to participate in this conversation.