DEV Community

Lev Eidelman Nagar
Lev Eidelman Nagar

Posted on

Creating Our First Controller

In my last post we set up Inertia and Adonis. Now that we have a solid foundation to build upon, let us continue fleshing out our CRM app.

Our First Controller

In my previous post we used a closure route to test everything worked end-to-end. This is fine for simple one-off routes (things like the "about" page for instance), but for more demanding routes, we'll usually reach for a controller.
Let us therefore use ace to scaffold a resourceful controller:

node ace make:controller user -r
Enter fullscreen mode Exit fullscreen mode

alt text

Take a moment to look at the new controller, Ace created for you. This is a basic template for our future CRUD operations:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class UsersController {
  public async index ({}: HttpContextContract) {
  }

  public async create ({}: HttpContextContract) {
  }

  public async store ({}: HttpContextContract) {
  }

  public async show ({}: HttpContextContract) {
  }

  public async edit ({}: HttpContextContract) {
  }

  public async update ({}: HttpContextContract) {
  }

  public async destroy ({}: HttpContextContract) {
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, let's connect some routes to the users controller.

Configuring Resource Routes

Open start/routes.ts and delete the route we previously created. Instead add this:

Route.resource('users', 'UsersController');
Enter fullscreen mode Exit fullscreen mode

This doesn't look like much, but let's see what routes were automatically created for us:

node ace list:routes
Enter fullscreen mode Exit fullscreen mode

alt text

Pretty neat! Adonis automatically created a route for each controller method.

Top comments (0)