Home  >  Q&A  >  body text

Implementing an optional two-way user relationship: a step-by-step guide

I have a user model and there is some relationship between these users.

Example: John is the father of Jack and Jill.

Jack and Jill are brothers and sisters.

Jack is a friend of Jacob and Joshua.

How can I fully realize this relationship? This is a mix of family relationships and friendships so I'm confused what is the best course of action?

P粉412533525P粉412533525184 days ago339

reply all(1)I'll reply

  • P粉178894235

    P粉1788942352024-04-02 00:57:51

    You need to make two models: User and Relationship. First, make the two models related (one-to-many relationship):

    Model: User

    public function relations()
    {
        return $this->hasMany(Relation::class);
    }

    Model:Relationship

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    Then in your relational model (remember to set this on your migrations too), you need to have four columns: user_one , user_two , type_one and type_two .

    For example: user_one: father's user id / user_two: son's user id, type_one: father / type_two: son.

    So be it.

    reply
    0
  • Cancelreply