This page looks best with JavaScript enabled

The Right Way to Receive Parameters in AdonisJS Controller

 ·   ·  ☕ 2 min read

Quickly and easily pass parameters to controller methods from your request.

See Start creating your backend application in AdonisJS to get started

You can quickly scaffold a controller in Adonis using the following command -

1
adonis make:controller Todo --type http

If you want to receive parameters from input, you would do the following -

1
2
3
4
5
6
7
8
class AccountController {
  async create({ request, auth, params, addParams }) {
    const data = request.all();
    /*
      ..
      ..
    */
  }

By destructuring assignment to variables within the function argument itself, you are doing two things -

  1. Provide clarity on the acceptable arguments
  2. Signal that only specified variables are allowed

In the above example -

  1. request, contains data that is passed by the caller. For example: data may be in JSON request for a POST request. This is automatically available to our method in the controller.

  2. params is also passed to the method by Adonis. This is any parameter passed through URL. route collects the parameter values and passes it to the controller method.
    The route may have the following URL, which is processed for params, and id received from caller is passed to the controller method.

    1
    
    Route.patch("/todo/:id", "TodoController.update");
    
  3. auth refers to authentication. This is a way of Adonis informing your method about the client status. You can now do the below to get logged in user details -

    1
    
    const user = auth.getUser();
    
  4. addParams is a custom parameter that is not provided by Adonis. You would have to pass an object with the same name for Adonis to make any sense of it and process it as ‘addParams’.

However, the rules are not enforced by the framework. Adonis 4.1 does not have types, and does not provide anything out of the box for paramter pre-validations.

You could do something akin to the below in your controller method for validation -

1
2
const { id } = params;
if (!id) throw "Id cannot be blank";
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things