Skip to content

GORM Hooks: BeforeCreate Not Triggered

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about GORM Hooks: BeforeCreate Not Triggered. We cover key concepts, practical examples, and best practices.

GORM lifecycle hooks -- Use GORM hooks (BeforeCreate, AfterFind) to run custom logic at specific points in the model lifecycle.

The Problem

GORM hooks are methods on a model struct. BeforeCreate must be named exactly BeforeCreate(tx *gorm.DB) error. Wrong signature = hook silently ignored.

Wrong

type User struct {
    ID       uint
    Password string
}
func (u User) BeforeCreate(tx *gorm.DB) { } // Value receiver, no error!

Output:

// Hook never called. Password stored as plain text.
type User struct { ID uint; Password string }
func (u *User) BeforeCreate(tx *gorm.DB) error {
    hashed, _ := bcrypt.GenerateFromPassword([]byte(u.Password), 12)
    u.Password = string(hashed)
    return nil
}

Output:

// Password hashed before insert

Prevention

  • Hooks must use pointer receiver (*User)
  • Hooks must return error
  • Available: Before/After Save, Create, Update, Delete, Find
  • Return error to abort operation
  • AfterFind runs after every query

Common Mistakes with gorm hooks

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What is the hook execution order?**

BeforeSave -> BeforeCreate -> INSERT -> AfterCreate -> AfterSave.

Can I skip hooks?

Yes. Use db.Session(&gorm.Session{SkipHooks: true}).

Do hooks run in transactions?

Yes. Same transaction as the operation.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro