Search code examples
mysqllaraveleloquent-relationship

How to implement optional two-way relationships for users?


I have a user model and these users have some sorts of relationships together.

Example: John is Jack and Jill's father.

Jack and Jill are siblings.

Jack is friend with Jacob and Joshua.

How can I implement this kind of relationship altogether? It's a mixture of family relationships and friendships so I'm confused what is the best practice for this?


Solution

  • you need to make two models : User and Relation. First, make two models related (one-many relationship):

    Model:User

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

    Model : Relation

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

    then in your Relation model(remember to set it on your Migration also) , you need to have four columns : user_one , user_two , type_one and type_two.

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

    there you go.