This package just takes the example from the the AdonisJS documentation about extending routes and adds an additional lookup parameter (the field to look up on) to it.
This package is for AdonisJS 4.x.
First install this package
adonis install adonis-route-model-binding
# or
npm install --save adonis-route-model-binding
# or
yarn add adonis-route-model-binding
Add the RouteModelBindingProvider to your start/app.js
file
const providers = [
...
'adonis-route-model-binding/providers/RouteModelBindingProvider',
]
Add the binding to a route that you have in your routes file:
Route.get('some/route/:userId', 'UserController.show')
.bind('App/Models/User', 'user', 'userId', 'id');
What does that mean? Below is an explanation of the list of parameters on the above .bind(..)
method in order.
-
App/Models/User
is the target model that you want to load -
user
is the key that this model will be bound to on therequest
object that gets passed into the controller -
userId
is the route parameter that we are using. The:userId
onsome/route/:userId
in this case -
Optional
id
is the database field we are going to look up the value ofuserId
in.id
is the default so you can leave this off unless you want to explicitly look up on another field.
Now in your controller you will have access to the user
object on the show()
method:
class UserController {
async show({ request, params, user }) {
// do something with user here
}
}
- Initial release
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION