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

Kris01's avatar

Laravel Nova\Eloquent Relationships

Hi,

I am working on a project, and the other guy that created the migrations, didn't specify the foreign keys of the tables, he just created them as integers.

As of now, I am trying to intagrate laravel nova, and it is throwing some errors on the relationships part. Is it possible that eloquent relationships don't work if the fk is assigned as int and not as foreign key?

0 likes
4 replies
ramonrietdijk's avatar

No, it does not matter if a column is not specified as a foreign key on the table. Showing some of your code would be helpful in order to resolve your errors.

Kris01's avatar

@ramonrietdijk I have A user table and a listing table. A user can have many listings but a listing can only belong to one user. my fk in the listing for the user is 'owner'. That being said, I am having some problems with laravel nova when defining these relationships. Inside the 'field' function of App\Nova\Listings

            BelongsTo::make('owner', 'owner', \App\Nova\User::class)

Inside The listing model

    public function owner(){
        return $this->belongsTo('App\Models\User', 'owner', 'id');
    }

and I am still getting 'Undefined property: App\Models\Listing::$owner'

ramonrietdijk's avatar
Level 30

@Kris01 This is likely because the field on your model is the same name as the relationship. If owner is really the foreign key on your table you should try to rename your relationship to ownerUser to see if that works.

public function ownerUser() {
    return $this->belongsTo('App\Models\User', 'owner', 'id');
}

Your Nova field would have to be updated as well

 BelongsTo::make('owner', 'ownerUser', \App\Nova\User::class)

However, I strongly recommend naming your foreign key owner_id to avoid naming collisions.

2 likes

Please or to participate in this conversation.