Skip to content

Start Here

Basic sample, user avatar

sh
node ace add @jrmc/adonis-attachment
sh
# Create a new migration file
node ace make:migration change_avatar_column_to_json --table=users
ts
// Within the migration file
protected tableName = 'users'

public async up() {
  this.schema.alterTable(this.tableName, (table) => {
    table.json('avatar').alter() 
  })
}
ts
// start/routes.ts
import router from '@adonisjs/core/services/router'

router.attachments() 
ts
// app/models/user.ts
import { BaseModel } from '@adonisjs/lucid/orm'
import { attachment } from '@jrmc/adonis-attachment'
import type { Attachment } from '@jrmc/adonis-attachment/types/attachment'

class User extends BaseModel {
  @attachment() 
  declare avatar: Attachment
}
ts
// app/controllers/users_controller.ts
import { attachmentManager } from '@jrmc/adonis-attachment'

class UsersController {
  public store({ request }: HttpContext) {
    const avatar = request.file('avatar')!
    const user = new User()

    user.avatar = await attachmentManager.createFromFile(avatar) 
    await user.save()
  }
}
edge
<img src="/attachments/{{ user.avatar.keyId }}" loading="lazy" alt="" />

Thumbnail

sh
npm install sharp
sh
pnpm install sharp
sh
yarn add sharp
ts
// config/attachment.ts
import { defineConfig } from '@jrmc/adonis-attachment'
import { InferConverters } from '@jrmc/adonis-attachment/types/config'

const attachmentConfig = defineConfig({
  converters: {
    thumbnail: { 
      format: 'webp', 
      resize: 300, 
    } 
  }
})
...
edge
<img src="/attachments/{{ user.avatar.keyId }}?variant=thumbnail" loading="lazy" alt="" />