Route Model Binding in Adonisjs v5
Oct 06, 2021For 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
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