saqueib
3 years ago

User can Follow Post and Category in Laravel

Posted 3 years ago by saqueib

I need to implement a follow system like twitter but with exception a user can follow many Post and can follow whole Category or a user can follow a User.

I have come up with this relationship. I am using Laravel 5.1

User Model

public function followers()
{
   return $this->belongsToMany('App\User', 'user_follows', 'user_id', 'follow_id');
}

public function follows()
{
   return $this->belongsToMany('App\User', 'user_follows', 'follow_id', 'user_id');
}

and for follow a Category

Category Model

public function followers()
{
   return $this->belongsToMany('App\User', 'category_follows', 'user_id', 'category_id');
}

and for Post is the same way, as you can see I need 3 tables (user_follows, category_follows, post_follows) to make this work.

I know there is Polymorphic Relation but I cant wrap my head around it. Please help how i can simplify it. once again below are the requirements

  • User can follow many Posts
  • User can follow many Category
  • User can follow many User

Please sign in or create an account to participate in this conversation.