Laravel 7 one to one relationship

Sagardhiman
2 min readApr 21, 2020

--

In this post, we’ll discuss one to one relations in laravel. Before going ahead we first discuss what is a relationship. A Relationship is a structure through which we can connect multiple tables like joins to get data from multiple tables which are connected through a key(foreign key).

Types Of Relationships:

  1. One To One
  2. One To Many
  3. Many To Many
  4. Has Many Through
  5. Has One Through
  6. One To One(Polymorphic)
  7. One To Many(Polymorphic)
  8. Many To Many(Polymorphic)

In this section, we’ll focus on One To One relationship let take an example, suppose we have a USER Table which contains users data, and each user can talk to another user(one user at a time). So here we need to keep a record so that we can get which user is talking to another.

If you have a question in mind that why we need two foreign keys to keep the relation between uses?

Let's start, suppose you need to get all the data related to particular users who are connected to each other. There are 2 ways to do this task. For example

class User extends Authenticatable

{

public function relation()

{

return $this->hasOne(Relation::class);

}

}

From the above code, the User table has a relation function which means uses has One To One a relation with another user which has stored in Relation Table as shown above.

class Relation extends Model

{

public function user()

{

return $this->belongsTo(User::class);

}

public function user2()

{

return $this->belongsTo(User::class, ‘player2_id’);

}

}

In the Relation table, you have 3 main fields id, user_id, player2_id. By default as per laravel rules if you don't pass arguments with belongsTo is treats user_id as the foreign key because we make the relationship with the User table.

Here user_id and player2_id are both foreign keys.

But if you need another field as a foreign key, you need to pass a parameter with belongsTo as shown above.

But the question is that what we do if need 2 foreign keys at the same time which belongs to a single primary key of another table. To deal with the situation we need to make 2 functions which belong to the User table as shown above.

<div > {{ $usersList->user->name }} </div>

<div > {{ $usersList->user2->name ?? ‘N/A’}} </div>

Thats how we can get data of both the users with relationship.

--

--