Now, let's add ability for users to follow one another. Add the code below to start/routes.js within the users group routes:

// start/routes.js'/follow/:id', 'UserController.follow')

This route takes the ID of the user we want to follow as a parameter.

Next, add the code below to UserController:

Table of Contents

    // app/Controllers/Http/UserController.js
    async follow ({ request, auth, response }) {
        // get currently authenticated user
        const user = auth.current.user
        // add to user's followers
        await user.following().attach(request.input('user_id'))
        return response.json({
            status: 'success',
            data: null

    Firstly, we get the currently authenticated user. Then we use the attach method (made available to us due to the belongs-to-many relationship we defined between User and Followers) to add the user with the ID specified to the list of users the authenticated user is following.

    Chimezie Enyinnaya

    19 posts

    Software Developer [PHP Laravel JavaScript NodeJS AdonisJS VueJS] | movie lover | run