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

SERVANT14's avatar

Relationship & Column, Same Name?

So, we currently have a polymorphic relationship like so:

| id | entity | entity_id |
| -- | ------ | --------- |
|  1 | box    | 12        |
|  2 | shoe   | 43        |

The relationship is defined like:

public function Entity()
{
    return $this->morphTo('Entity', 'entity', 'entity_id');
}

It seems because of the case-difference, we can pull the column and relation values like:

$this->entity; // 12
$this->Entity; // Box

But, it looks like when we got to eager-load the relationship, it blows up:

Thing::with('Entity'); // Undefined property: App\Thing::$entity
$thing->load('Entity'); // Undefined property: App\Thing::$entity

Anyone know what that undefined property error is telling me? Why does lazy-loading work, but not eager-loading?

(I'm trying to see if we can avoid renaming this for now).

0 likes
4 replies
automica's avatar
automica
Best Answer
Level 54

@servant14 i'm not a big fan of having to remember whether to use upper or lower case.

i'd prefer to have id, name, entity_id as column names and solves the clash of names.

I know you are trying to avoid the rename but would suggest following convention will save you the time it takes to solve it.

SERVANT14's avatar

Yea, I totally agree. In this case, we don't have control over the database column names. So, I've decided to rename the relationship to ForEntity for this issue. Found it actually won't be that bad 😅. It's understandable why Laravel doesn't want those to match. It's a bit confusing for humans too :)

Thanks man!

automica's avatar

@servant14 apparently (after a google) you can spoof the same of the column by using a $maps array in your model

eg

protected $maps = [
  'dbCol1' => 'coolName1',
  'dbCol2' => 'coolName2'
];

That might mean you could use 'name' instead of 'entity' and then you can use 'entity' for your relationship.

I can't find any documentation about this but there are several topics on laracasts so might be worth a look.

see https://medium.com/@steno983/laravel-models-column-alias-c48a75065fb9

Please or to participate in this conversation.