Before we move to add the functionality to follow and unfollow users. Let's first make it possible for users to see those they can follow. Add the code below to start/routes.js above the user profile route:

// start/routes.js

Route.group(() => {
    Route.get('/users_to_follow', 'UserController.usersToFollow');
})
    .prefix('users')
    .middleware(['auth:jwt'])

Next, define the usersToFollow method. Add the code below to UserController:

// app/Controllers/Http/UserController.js

async usersToFollow ({ params, auth, response }) {
    // get currently authenticated user
    const user = auth.current.user

    // get the IDs of users the currently authenticated user is already following
    const usersAlreadyFollowing = await user.following().ids()

    // fetch users the currently authenticated user is not already following
    const usersToFollow = await User.query()
        .whereNot('id', user.id)
        .whereNotIn('id', usersAlreadyFollowing)
        .pick(3)

    return response.json({
        status: 'success',
        data: usersToFollow
    })
}

First, we get the currently authenticated user. Then we get an array of IDs of users the user is already following. Using these IDs, we perform a query using the whereNotIn to filter the users to those whose IDs are not in the array of IDs. That way, users a user is already following won't be shown for him/her to follow again. We also exclude the currently authenticated user from the results as it doesn't make sense to tell a user to follow himself/herself. Then we pick only the first 3 rows from the results.

Table of Contents

    Finally, we return a JSON object with the users to follow.

    Chimezie Enyinnaya

    20 posts

    Software Developer [PHP Laravel JavaScript NodeJS AdonisJS VueJS] | movie lover | run http://openlaravel.com