We have added the abilities for users to edit their profile and upload profile picture. Now let's fetch user's profile.

As usual, we'll start by defining the route. Add the line below to start/routes.js after the entire user account route group:

// start/routes.js

Route.get(':username', 'UserController.showProfile')

This route takes a username as the route parameter. This makes the route dynamic as different usernames can be passed to it. An example of this route will be something like http://example.com/mezie.

Table of Contents

    Note: Because this is more or less a wildcard route, it should be defined at the end of every other routes so as not to take precedence over some routes.

    Next, let's create the showProfile method. Add the code below in UserController:

    // app/Controllers/Http/UserController.js
    async showProfile ({ request, params, response }) {
        try {
            const user = await User.query()
                .where('username', params.username)
                .with('tweets', builder => {
                .with('favorites.tweet', builder => {
            return response.json({
                status: 'success',
                data: user
        } catch (error) {
            return response.status(404).json({
                status: 'error',
                message: 'User not found'

    Route parameters are available through the params object. To get the value of a parameter, we simply do something like params.username. The parameter name must match the name used when defining the route. So, we fetch the user from the database where the username matches the username parameter supplied in the URL. Calling the firstOrFail method will return the first user that matches the where clause and return an error if the username supplied was not found in the database. The rest of the queries are identical to those in me method we defined in the update user profile lesson.

    Chimezie Enyinnaya

    16 posts

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