Hooks are methods defined on your model struct that GORM calls automatically at specific points in the lifecycle of a database operation. You can use them to enforce business rules, update related data, or abort an operation by returning an error.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/go-gorm/gorm/llms.txt
Use this file to discover all available pages before exploring further.
Available hooks
GORM supports hooks for create, save, update, delete, and query operations.Create hooks
Create hooks
Executed in this order:
BeforeSaveBeforeCreate- create record in database
AfterCreateAfterSave
Update hooks
Update hooks
Executed in this order:
BeforeSaveBeforeUpdate- update record in database
AfterUpdateAfterSave
Delete hooks
Delete hooks
Executed in this order:
BeforeDelete- delete record from database
AfterDelete
Query hooks
Query hooks
Executed after the query:
AfterFind
Defining a hook
Define a hook as a pointer-receiver method on your model struct. The method must accept*gorm.DB and return error.
Aborting an operation
Return a non-nil error from any hook to abort the operation. GORM rolls back the transaction and propagates the error to the caller.Using tx inside hooks
Thetx parameter inside a hook shares the same transaction as the triggering operation. Use it to perform additional queries that must succeed or fail together with the main operation.
All hook signatures
Skipping hooks
Create a session withSkipHooks: true to bypass all hooks for that operation.
UpdateColumn and UpdateColumns skip hooks by default — they bypass the callback pipeline entirely and write directly to the database.Registering callbacks programmatically
Beyond model methods, you can register callbacks globally on thedb instance using the callback manager. This is useful for cross-cutting concerns like auditing or tracing.
Before, After, Match, Register, Remove, and Replace methods for fine-grained control over execution order.