Make user email field unique

Viewed 49

Following is my entiry defined

type User struct {
    gorm.Model
    FirstName string `json:"first_name"  binding:"required"`
    LastName  string `json:"last_name" binding:"required"`
    Email     string `json:"email" binding:"required,email" gorm:"unique,not null"`
    Phone     string `json:"phone" binding:"required"`
    Password  string `json:"password" binding:"required"`
}

Every thing work fine, but it still accept duplicated emails. I also tried unique_index but that isn't working as well.

1 Answers

There is a little typo on your code,

type User struct {
    gorm.Model
    FirstName string `json:"first_name"  binding:"required"`
    LastName  string `json:"last_name" binding:"required"`
    Email     string `json:"email" binding:"required,email" gorm:"unique,{Over here}not null"`
    Phone     string `json:"phone" binding:"required"`
    Password  string `json:"password" binding:"required"`
}

Change the comma after unique to semicolon and it should work.

type User struct {
    gorm.Model
    FirstName string `json:"first_name"  binding:"required"`
    LastName  string `json:"last_name" binding:"required"`
    Email     string `json:"email" binding:"required,email" gorm:"unique;not null"`
    Phone     string `json:"phone" binding:"required"`
    Password  string `json:"password" binding:"required"`
}
Related