2

I was wondering what the best way would be to set up a follow system were a user can follow another user. Can it be as simple as creating a followers table and inserting id's of users following the id of the other user? Thanks.

GarethFrazer
  • 75
  • 1
  • 1
  • 13
  • 2
    Just a friendly tip, you may want to read over this page: [The How-To-Ask Guide](https://stackoverflow.com/help/how-to-ask) so you can always be sure that your questions are easily answerable and as clear as possible. Be sure to include any efforts you've made to fix the problem you're having, and what happened when you attempted those fixes. Also don't forget to your show code and any error messages! – Matt C Apr 26 '16 at 22:13
  • Thanks for the heads up. I just wasn't really sure with this at all. There was a laracasts video on it but it's very outdated now and wouldn't work properly with Laravel 5.2 – GarethFrazer Apr 27 '16 at 09:13
  • Why is this closed? The question is pretty clear and a needed one. The questioner is looking for the logic behind the code, not asking for the entire code. I think stackoverflow MUST be more userfriendly in this type of topics. – Agil Dec 14 '17 at 14:08

1 Answers1

8

Yes it's very easy to create this kind of feat with laravel.

I suggest you this one : Friendship system with Laravel : Many to Many relationship

all you have to do is replace friend by follower.

Example :

Create a table :

followers: id, user_id, follower_id.

in your User model you will have this relationship

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

function follow(User $user) {
   $this->followers()->attach($user->id);
}

function unfollow(User $user) {
   $this->followers()->detach($user->id);
}

Get User 1 Followers :

$user = User::find(1);
$user->followers;

User 1 Follow User 2

$user1 = User::find(1);
$user2 = User::find(2);
$user1->follow($user2);

User 1 Unfollow User 2

$user1 = User::find(1);
$user2 = User::find(2);
$user1->unfollow($user2);
Community
  • 1
  • 1
zorx
  • 1,861
  • 14
  • 16
  • How would I implement this with a follow button for each user? – GarethFrazer Apr 27 '16 at 09:55
  • @zorx I would like to ask if I have to have the followers table in orther to save all following actions or is there any other way to work this problem around? I know it is probably a dumb question, but It is already clear how you do this with the extra table, I don't find the logical way of asking the question. It's just my database tabels, there are already too many of them :/ – Agil Dec 14 '17 at 15:14
  • BTW there is one thing that rly bothers me. How do you detect if the user already followes the other one? that way a user can't follow the other one more than once? – Agil Dec 15 '17 at 09:58