Skip to content
Advertisement

Laravel 5.1 – BelongsTo relationship returns null

AppUser

JavaScript

AppUserStatus

JavaScript

I already have the $user object from a simple User::find() query with some fields, then I try to access the status object by lazy loading it with $user->load('status') method.

I’m following the docs, but it seems useless since $user->status still returns null.

JavaScript

What am I doing wrong?

——— SOLUTION ———

Actually, to lazy load any relationship, the foreign key value needs to be stored in the model object.

In my find operation, I wasn’t querying the user_status_id field. When I added this field into the query, the $user->status statement started to return the UserStatus model.

I don’t think this information is written on the Laravel docs, it may be simple, but it took me some time to figure that out.

Advertisement

Answer

Actually, to lazy load any relationship, the foreign key value needs to be stored in the model object.

In my find operation, I wasn’t querying the user_status_id field. When I added this field into the query, the $user->status statement started to return the UserStatus model.

I don’t think this information is written on the Laravel docs, it may be simple, but it took me some time to figure that out.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement