Go to Home

Route Model Binding in Adonisjs v5

For any CRUD application, generally, we'll have a scenario where we'll try to retrieve a record from the database based on the identifier passed on the URL. For example, we'll have routes like this

and controller method like this

Above we can clearly see we're performing same identifier check with Post model for show(), update() and destroy() methods. By using route model binding, we can eliminate the code duplication easily.

Implementation

Route model binding is a mechanism of binding/injecting the model instance directly into your route.

First, we have to define bind() method for routes. For that, we have to create a provider and register our bind() method using Route macros.

node ace make:provider RouteModelProvider

Now, let's open the RouteModelProvider.ts file add the necessary code under boot() method.

Kindly note, above I've defined both the Route.bind() and Route.resource().bind(). Now, we've to inform typescript that we have registered a new method called bind() on routes. We can do that by performing declaration merging and add the property to the RouteContract interface. Create a new file at path contracts/route.ts and paste the following contents inside it.

That's it. We've successfully configured all the necessary items for route model binding. Now we can call our bind() method on routes like this

Since we have bound the model on the route, we can directly retrieve a model instance from controller methods like below

So simple and clean. That's the beauty of route model binding.

Happy Coding

One email per week. No spam ever.

Subscribe