Getting Started
CLI
Request handling
- Routing
- Action Controller
- Resources
- Context
- Request Binding
- Middleware
- Error Handling
- Sessions
- Cookies
Frontend
Database
- Getting started with Pop
- Soda CLI
- Database Configuration
- Buffalo Integration
- Models
- Generators
- Migrations
- Fizz
- Mutations
- Querying
- Raw Queries
- Callbacks
- Scoping
- Associations and Relationships
- One to one associations
- One to many associations
Guides
- API Applications
- File Uploads
- Background Job Workers
- Mailers
- Tasks
- Local Authentication
- Third Party Authentication
- Events
- Go Modules
- Localization
- Logging
- Template Engines
- Testing
- Videos
Deploy
Callbacks
Database
Callbacks
Pop provides a means to execute code before and after database operations. This is done by defining specific methods for your models.
For example, to hash a user password you may want to define the following method:
type User struct {
ID uuid.UUID
Email string
Password string
}
func (u *User) BeforeCreate(tx *pop.Connection) error {
hash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return errors.WithStack(err)
}
u.Password = string(hash)
return nil
}
In the above example, when the connection’s Save
method is called with a User
, the BeforeCreate
method
will be called before writing to the database.
The available callbacks include:
- BeforeSave
- BeforeCreate
- BeforeUpdate
- BeforeDestroy
- BeforeValidate
- AfterSave
- AfterCreate
- AfterUpdate
- AfterDestroy
- AfterFind
Related Content
- Models - Define a database model.