Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AndreiTelteu/ec8c8d077a8b77936ad53a7e66e6e51a to your computer and use it in GitHub Desktop.
Save AndreiTelteu/ec8c8d077a8b77936ad53a7e66e6e51a to your computer and use it in GitHub Desktop.
User following relationships for Laravel 5.2 with jenssegers/laravel-mongodb database driver

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');
	}

Usage

  • 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';

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment