Caesar
Caesar

Reputation: 25

I'm trying to get the Followers of a specific user with Eloquent, from a many to many relationship in Laravel

I want to create a function that returns all the followers of a specific user. I tried using this method:

    public function getFollowers($id){
            $user=User::find($id);
            $followers=$user->followers();
            return response()->json([
                'data' => $followers,
            ]);
    }

But it returns this.

{
"data": {
    "withTimestamps": false
}

}

In my user model I have this functions:

public function following(){ //users that are followed by this user
    return $this->belongsToMany('App\Models\User', 'followers', 'user_id', 'follower_id');
}
public function followers(){  //users that follow this user
    return $this->belongsToMany('App\Models\User', 'followers', 'follower_id', 'user_id');
}

And the design of the tables are these:

Followers: followers table

Users: Users table

Upvotes: 0

Views: 30

Answers (1)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

change code to

public function getFollowers($id) 
{
    $user = User::find($id);
    $followers = $user->followers()->get();
    return response()->json([
        'data' => $followers,
    ]);
}

Upvotes: 2

Related Questions