User following relationships for Laravel 5.2 with jenssegers/laravel-mongodb
Just add this belongsToMany relations to your user model:
/*
* One user follows many users
*/
public function following()
{
return $this->belongsToMany(self::class, null, 'followers', 'following');
}
/*
* One user has many followers
*/
public function followers()
{
return $this->belongsToMany(self::class, null, 'following', 'followers');
}
- getting users that this user follows:
$user->following
or$user->following()->get()
- getting this user's followers:
$user->followers
or$user->followers()->get()
- count this user followers
count($user->followers)
- making user1 to follow user2:
$user1->following()->save($user2)
or$user1->following()->attach($user2)
- making user1 to unfollow user2:
$user1->following()->detach($user2)
- checking if user1 follows user2, using in_array:
if (in_array($user2->_id, $user1->following)) echo 'following';
- checking if user1 follows user2, using the Query Builder:
if ($user1->following()->where('_id', $user2->_id)->count() !== 0) echo 'following';
- belongsToMany laravel documentation
- belongsToMany jenssegers/laravel-mongodb documentation
- Thanks to macghriogair from StackOverflow for his answer