You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.

Controllers

While closures might be enough to handle route logic for small applications, when your application starts to grow, it becomes useful to organize application logic elsewhere.

This is where Controllers come into play.

Controllers attach to one or many routes, grouping related request handling logic into single files, and are the common point of interaction between your models, views and any other services you may need.

A controller’s only job is to respond to a HTTP request. Do not use them internally by requiring them inside different files.

Creating Controllers

To create a new controller, use the make:controller command:

# HTTP Controller
> adonis make:controller User --type http

# WS Controller
> adonis make:controller User --type ws

# Will use an Admin subfolder
> adonis make:controller Admin/User

This command creates a boilerplate file in the App/Controllers/{TYPE} folder:

app/Controllers/Http/UserController.js
'use strict'

class UserController {
  //
}

module.exports = UserController
Use the --resource flag to create a resourceful controller.

Using a Controller

A controller can only be accessed from a route.

This is done by referencing the controller as a string in your route definition:

app/routes.js
Route.get(url, 'UserController.index')

The part before the dot is a reference to the controller file (e.g. UserController), and is by default namespaced to App/Controllers/Http.

The part after the dot is the name of the method you want to call inside this controller (e.g. index).

For example:

app/routes.js
// app/Controllers/Http/UserController -> index()
Route.get(url, 'UserController.index')

// app/Controllers/Http/Admin/UserController -> store()
Route.post(url, 'Admin/UserController.store')

// app/MyOwnControllers/UserController -> index()
Route.post(url, 'App/MyOwnControllers/UserController.index')

As your defined controller methods are route handlers, they will receive the HTTP Context as an argument:

app/Controllers/Http/UserController.js
'use strict'

class UserController {
  index ({ request, response }) {
    //
  }
}

module.exports = UserController