Reputation: 25
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:
Upvotes: 0
Views: 30
Reputation: 8618
change code to
public function getFollowers($id)
{
$user = User::find($id);
$followers = $user->followers()->get();
return response()->json([
'data' => $followers,
]);
}
Upvotes: 2