Kitthaven's avatar

Trouble loading relationship

I'm trying to load a relationship in one of my controllers and it's not working. The thing is I have set up relationships before and they're all working correctly but for some reason this one is just not. Even copying directly from a relationship of the same type... hopefully someone else has an idea?

For context I am creating a virtual pet site.

I have a UserAdopt model for owned adopts. I have an Adopt model for adopts created through the admin area. The UserAdopt BelongsTo the Adopt model using the foreign key 'adopt'.

Here is the relationship in UserAdopt:

public function adopt(): BelongsTo {
        return $this->belongsTo(Adopt::class, 'adopt');
    }

This is how I am calling it in the controller to display on the adopt profile:

'adopt' => UserAdopt::with(['user', 'originalOwner', 'adopt'])->find($adopt->id),

The other 2 relationships work just fine.

I have tried both eager and lazy loading the 'adopt' relationship by itself and then dumping the data and it always fails and just dumps the ID number found in the adopt column, so it's not loading the model correctly.

In the migration, this is how I have set up the foreign ID:

$table->foreignIdFor(Adopt::class, 'adopt')->constrained()->cascadeOnDelete();

I know that it is connected properly on a database level because when I use mySQL I can click the ID number to go to the correct item in the adopts table.

I have also tried changing the name of the function from 'adopt' to something else just in case it was conflicting with something but no matter what I call it it still doesn't load correctly.

Does anyone have any ideas? Thank you...

0 likes
2 replies
tykus's avatar

@kitthaven you are getting an ID back because the relationship method has the same name as the foreign key column; so Eloquent has matched the column name before the magic relationship property.

This is the reason for the _id suffix convention we use for foreign keys - it allows you to use the natural word to describe the relationship, while the implementation detail of the actual column name is less important.

You have two choices to remediate this (i) change the name of the adopt column to something else - convention would suggest adopt_id is appropriate, or (ii) change the name of the relationship so it does not collide with the column name, e.g. adoptee().

My personal preference would be (i).

1 like

Please or to participate in this conversation.