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

chanhhuynh144's avatar

Relationship returns null for some records

I have 2 models: TopHistory and User I using UUID for id column in User table, and user_id column in TopHistory. In TopHistory model. I have create a relationship method

public function user() {
        return $this->belongsTo(User::class, 'user_id', 'id');
}

I have 4 user and 4 history records. Each history record, I use $user->id itself to add the user_id field. And I try return TopHistory::with('user')->get(). But only 3 record return user data. Just have one record return null. I am sure the user_id field values of the 4 history records all exist user. Someone please help me solve this. Thanks

0 likes
10 replies
nexxai's avatar

As @vincent15000 mentioned, what does your actual database have stored? Is it possible that when one of the records was being saved, the ID wasn't stored (e.g. because you didn't have it in your $fillable array at the time)?

1 like
chanhhuynh144's avatar

@vincent15000 @nexxai Sorry for late reply, sir. I have checked in Workbench. The user_id field in all history records has been populated. I tried copying them and writing a search query in the user table, of course the results returned.

1 like
gych's avatar

@Emjiz Try like this, foreign key first than owner key

public function user() {
        return $this->belongsTo(User::class,  'id',  'user_id');
}
1 like
gych's avatar

@vincent15000 I'm just giving a potential solution based on the post of the OP. I also state foreign key first than owner key

1 like
JussiMannisto's avatar

@gych You think the foreign key is id and the primary key is user_id? This is obviously wrong. They even explained the relation in the original post.

2 likes
gych's avatar

@JussiMannisto You're right I just re-read the post again and the relation is created in the Tophistory model that has the clumn user_id therefor foreignkey should be user_id and not id

Snapey's avatar

If you would like a model to use a UUID key instead of an auto-incrementing integer key, you may use the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the model. Of course, you should ensure that the model has a UUID equivalent primary key column

Have you added this trait?

Also, you should not specify the foreign and primary keys in the relationship since there is a very good chance of getting them the wrong way around. If you are using conventions of id for primary key and user_id for the fk pointing to the user model then don't specify the keys.

public function user() {
        return $this->belongsTo(User::class);
}

Please or to participate in this conversation.