A Deep Understanding of Laravel One To One Relationship

Solaiman Khan
3 min readAug 27, 2021

--

One to One relationship are the easiest relationship in Laravel Eloquent Relationships. However many people struggle to understand especially the inverse part, belongsTo to be exact. In this article i will briefly describe both way of this relationship.

#Table & Its Stecture
Suppose I have two Model one is User and another is Phone. Table Stecture are given below.

!Important — Here both table has id as primary key.

#HasOne

A User has a phone number, so it relation type will be hasOne.
Lets define that in ‘UserModel’

Here, Laravel Eloquent determines the foreign key of the relationship based on the parent model name. In this case, the Phone model is automatically assumed to have a user_id foreign key as our table stecture describe.

Great going, lets dive deep..

If our PhoneModel does not have a foreign key following the naming convention. If our PhoneModel has a different name rather than user_id?

Lets assume our PhoneModel has a foreign key column named abcd_id Then you can pass that column name in second parameter.

In this case our UserModel has a foreign key column name is phone_id

Now another senario is if our UserModel has a different name of xyz_idrather than phone_idthan what? No worries, you can pass it as a third parameter.

This pattern happens under the hood. Laravel do it for you but if there is a different naming convention other than laravel then you have to explicitly say it.

#BelongsTo

A Phone is belongs to a user, so it relation type will be inverse of hasOne namedbelongsTo.
Lets define that in ‘PhoneModel’

Here Laravel Eloquent will attempt to find a UserModel that has an id which matches the user_id column on the PhoneModel.

We are done but lets go beyond this..

Lets Assume our UserModel has a different primary key nameduid rather than idalso the PhoneModel has a other foreign key column namedxxxx_id rather thanuser_id.Look at the given picture.

Don’t worry, you can pass both this name as a parameter likexxxx_idas second parameter and uidas third parameter.

If you do not have a UserModel with a different primary key rather thanid then you don’t need to pass as third parameter. Done!

I hope that this article gave you a brief understanding of easy yet tricky relationship in laravel eloquent relationships. Feel free to leave a comment if you have any feedback, questions and thanks for reading.

Jazāk Allāhu Khayran!

--

--

Solaiman Khan
Solaiman Khan

Written by Solaiman Khan

Slave to Allah, a son, husband, brother, friend, and human being with humanity

No responses yet