Has one relationship


#1

I felt a issue today. Does Lucid return null on hasone/belongsto relationship when no related data found??

user =await User.find(id) 
profile = await user.profile().fetch()

i was sending that to view
Kept throwing toJSON() on null. Had to push condition on that.

But shouldn’t it return a underlying whatever (object/collection) lucid provide rather than null even if no profile found for user ???


#2

It’s not an issue. The system has to handle possible use cases a program can be in.

If user profile is optional and doesn’t exists in some cases, then you should handle it.

For example: Let’s say I am creating a UI, in which I show the user profile to the user. However, if they don’t have a profile yet, then I would like to show them some generic message with an action button to create a profile.

So handling these use cases is also the need of creating a proper user flow.

@if(!user.profile)
   <a href=""> Create profile </a>
@else
    {-- show it the way you want --}
@endif

#3

when it’s hasmany relationship it works great, it returns a lucid object even if no related data exists, then toJSON() or other serializer return empty array.Doesn’t throw any error, if dont check , in most of cases.