Has one relationship


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 ???


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.

   <a href=""> Create profile </a>
    {-- show it the way you want --}


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.