Agil
Agil

Reputation: 396

How to get followers and following users in single table

I did follow functionality, it has a followers table which includes these columns:

user_id
follower_id

this works perfect, there is a function in user Model too:

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

I can get all the followers if I want, with this basic function. But what I'm trying is to get is whome, the user follows(following). and than I will get posts made by that user and other stuff. So probably there needs to be a following function. But I couldn't work it out, I guess I'm a little tired, any help is appreciated.

Laravel 5.4

Upvotes: 1

Views: 158

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Define the relationship:

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

Use it:

$follows = $user->follows;

Upvotes: 2

Related Questions