Dynamic import of Models
Package version
V5
Node.js and npm version
Nodejs :14.15, npm : 6.14.8
Sample Code (to reproduce the issue)
I want to create FindById middleware to get record
Route.get('/:id', 'TemplateController.show').middleware('findById:Template')
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
export default class FindById {
public async handle(
{ request, response }: HttpContextContract,
next: () => Promise<void>,
model: string
) {
// code for middleware goes here. ABOVE THE NEXT CALL
const id = request.param('id')
const Instance = await import(`App/Models/${model}`)
const record = await Instance.query().where('id', id).first()
if (!record) {
return response.notFound({ message: `${model} not found.` })
}
request[model.toLowerCase()] = record
await next()
}
}
BONUS (a sample repo to reproduce the issue)
its throwing following error

my codebase Model:

Cannot reproduce. Please provide a sample project repo to help reproduce the issue
Closing since no response from the issue reporter and not actionable as well
Hi. Although it already closed, with relative path works for me:
const instance = await import(`../../Models/${model}`).then((m) => m.default)
const record = await instance.query().where('id', id).first()
Sure! Here's your GitHub issue answer rewritten in clear, professional English, suitable for submitting as a helpful comment or solution:
✅ Dynamic Model Import in AdonisJS Without Manual Imports
🎯 Problem
Sometimes we need to load AdonisJS models dynamically—without importing each one manually—especially when building generic services or factories.
🛠️ Solution
-
Create a preload file using the AdonisJS CLI:
node ace make:preload modelThis will create a file at:
start/model.ts -
Edit
start/model.tswith the following code:// start/model.ts declare global { var getModel: (name: string) => Promise<any> } global.getModel = async (name: string) => { const module = await import(`../app/Models/${name}.ts`) return module.default }📌 Note: The relative path assumes your models are located in
app/Models/. Adjust as needed based on your project structure.
✅ Usage Example
You can now dynamically load and use any model like this:
const User = await getModel('User')
const users = await User.all()
This removes the need to manually import models in each file.
💡 Optional: Fallback for Production Builds
If you're running a production build (node build) and your files are compiled to .js, you can add a fallback:
global.getModel = async (name: string) => {
try {
const module = await import(`../app/Models/${name}.ts`)
return module.default
} catch {
const module = await import(`../app/Models/${name}.js`)
return module.default
}
}
📦 Benefits
- No need to import each model manually
- Cleaner and more scalable code
- Great for dynamic services, admin generators, or resolving models by name