Use this file to discover all available pages before exploring further.
Controllers are classes that group related request handling logic together. They help keep your routes file clean and make your code more maintainable.
Create a controller with RESTful methods using the --resource flag:
node ace make:controller User --resource
This generates a controller with all RESTful methods:
import type { HttpContext } from '@adonisjs/core/http'export default class UsersController { /** * Display a list of resource */ async index({}: HttpContext) {} /** * Display form to create a new record */ async create({}: HttpContext) {} /** * Handle form submission for the create action */ async store({ request }: HttpContext) {} /** * Show individual record */ async show({ params }: HttpContext) {} /** * Edit individual record */ async edit({ params }: HttpContext) {} /** * Handle form submission for the edit action */ async update({ params, request }: HttpContext) {} /** * Delete record */ async destroy({ params }: HttpContext) {}}
Each controller should handle a single resource. If your controller is getting too large, consider splitting it into multiple controllers or extracting logic into services.
Use services for business logic
Controllers should be thin and delegate complex business logic to service classes. This makes your code more testable and maintainable.
Validate input in controllers
Always validate user input using request validators before processing:
async store({ request }: HttpContext) { const data = await request.validateUsing(createUserValidator) const user = await User.create(data) return { user }}
Use consistent naming
Follow RESTful naming conventions for controller methods: