Skip to content

Email Verification

Security

Email Verification

Introduction

Many web applications require users to confirm their email address before they use sensitive features or receive transactional mail. For example, a store might let a new user browse right away, but wait until they've verified their address before they may pay. Laravel can email the user a signed verification link, check the link when they open it, and keep unverified users out of the routes you choose, while your application stays in charge of the routes and the pages.

Before you start, set up authentication, so users can log in.

Setting up verification

Laravel reads the user's address from the Email field of your User model and the verification time from its EmailVerifiedAt field, and sets the email_verified_at column when the user verifies. New applications already have both fields on User, in models/user.go, and their users migration creates the nullable email_verified_at column:

1package models
2 
3import "time"
4 
5type User struct {
6 ID int64 `json:"id"`
7 Email string `json:"email"`
8 EmailVerifiedAt *time.Time `json:"email_verified_at"`
9 // ...
10}
1package models
2 
3import "time"
4 
5type User struct {
6 ID int64 `json:"id"`
7 Email string `json:"email"`
8 EmailVerifiedAt *time.Time `json:"email_verified_at"`
9 // ...
10}

Laravel sends verification links with the mail system, to the address that your User model's MailAddress method returns. Add this method to your User model in models/user.go, as the mail guide's section on recipients describes:

1func (u User) MailAddress() mail.Address {
2 return mail.Address{Name: u.Name, Email: u.Email}
3}
1func (u User) MailAddress() mail.Address {
2 return mail.Address{Name: u.Name, Email: u.Email}
3}

Email verification needs three routes behind Authenticate, in your routes/web.go: a notice page that asks the user to check their inbox, a route that sends a new verification email, and the route that handles the link the user clicks. Throttle the resend and verify routes, so one user can't flood their inbox and no one can guess links. Give each throttle a bucket of its own, so a user who has asked for six new links may still open the latest one:

1import (
2 "go.laravel.com/auth"
3 "go.laravel.com/middleware"
4 "go.laravel.com/routing"
5 
6 "app/handlers/verification"
7)
8 
9route.Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {
10 route.Get("/email/verify", verification.Notice).Name("verification.notice")
11 
12 route.Post("/email/verification-notification", verification.Resend).
13 Middleware(middleware.ThrottlePerMinute(6).WithBucket("verification-resend"))
14 
15 route.Get("/email/verify/{id}/{hash}", verification.Verify).Name("verification.verify").
16 Middleware(middleware.ThrottlePerMinute(6).WithBucket("verification-verify"))
17})
1import (
2 "go.laravel.com/auth"
3 "go.laravel.com/middleware"
4 "go.laravel.com/routing"
5 
6 "app/handlers/verification"
7)
8 
9route.Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {
10 route.Get("/email/verify", verification.Notice).Name("verification.notice")
11 
12 route.Post("/email/verification-notification", verification.Resend).
13 Middleware(middleware.ThrottlePerMinute(6).WithBucket("verification-resend"))
14 
15 route.Get("/email/verify/{id}/{hash}", verification.Verify).Name("verification.verify").
16 Middleware(middleware.ThrottlePerMinute(6).WithBucket("verification-verify"))
17})

Laravel finds the notice page and the verification route by their names, so name them verification.notice and verification.verify. Each verification link carries the user's ID and a hash of their email address in the {id} and {hash} parameters, so the verification.verify route needs both. If it lacks either one, the application refuses to start and reports the missing parameter.

Send the first link as soon as a user signs up, by passing the new user to auth.SendVerificationLink. This sign-up handler creates the user, logs them in, and sends the link:

1package registrations
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/hash"
6 "go.laravel.com/model"
7 "go.laravel.com/validation"
8 "go.laravel.com/validation/rule"
9 "go.laravel.com/web"
10 
11 "app/models"
12)
13 
14type SignUp struct {
15 Name string `json:"name"`
16 Email string `json:"email" transform:"lowercase"`
17 Password string `json:"password"`
18}
19 
20func (f *SignUp) Rules() validation.Rules {
21 return validation.For(f,
22 rule.Field(&f.Name, rule.Required, rule.Max(255)),
23 rule.Field(&f.Email, rule.Required, rule.Email, model.Unique[models.User]()),
24 rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
25 )
26}
27 
28func Store(r *web.Request) *web.Response {
29 form, err := r.Validate[SignUp]()
30 if err != nil {
31 return web.Fail(err)
32 }
33 
34 hashed, err := hash.Make(r, form.Password)
35 if err != nil {
36 return web.Fail(err)
37 }
38 
39 user := models.User{Name: form.Name, Email: form.Email, Password: hashed}
40 if err := model.Create(r, &user); err != nil {
41 return web.Fail(err)
42 }
43 
44 if err := auth.Login(r, &user, false); err != nil {
45 return web.Fail(err)
46 }
47 
48 if err := auth.SendVerificationLink(r, &user); err != nil {
49 return web.Fail(err)
50 }
51 
52 return web.RedirectRoute("dashboard")
53}
1package registrations
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/hash"
6 "go.laravel.com/model"
7 "go.laravel.com/validation"
8 "go.laravel.com/validation/rule"
9 "go.laravel.com/web"
10 
11 "app/models"
12)
13 
14type SignUp struct {
15 Name string `json:"name"`
16 Email string `json:"email" transform:"lowercase"`
17 Password string `json:"password"`
18}
19 
20func (f *SignUp) Rules() validation.Rules {
21 return validation.For(f,
22 rule.Field(&f.Name, rule.Required, rule.Max(255)),
23 rule.Field(&f.Email, rule.Required, rule.Email, model.Unique[models.User]()),
24 rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
25 )
26}
27 
28func Store(r *web.Request) *web.Response {
29 form, err := r.Validate[SignUp]()
30 if err != nil {
31 return web.Fail(err)
32 }
33 
34 hashed, err := hash.Make(r, form.Password)
35 if err != nil {
36 return web.Fail(err)
37 }
38 
39 user := models.User{Name: form.Name, Email: form.Email, Password: hashed}
40 if err := model.Create(r, &user); err != nil {
41 return web.Fail(err)
42 }
43 
44 if err := auth.Login(r, &user, false); err != nil {
45 return web.Fail(err)
46 }
47 
48 if err := auth.SendVerificationLink(r, &user); err != nil {
49 return web.Fail(err)
50 }
51 
52 return web.RedirectRoute("dashboard")
53}

SendVerificationLink queues an auth.VerificationEmail with a signed link that works for 60 minutes, so the request doesn't wait for your mail provider, and a worker sends it. It does nothing if the user's email is already verified.

Emails get lost and links expire, so the notice page has a form that asks for a new link, which posts to the Resend handler. Both handlers send a user who has already verified their email, such as in another tab, on to the page they wanted:

1package verification
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/inertia"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Notice(r *web.Request) *web.Response {
12 user := r.User[models.User]()
13 if user.EmailVerifiedAt != nil {
14 return auth.RedirectIntended("/dashboard")
15 }
16 
17 return inertia.Render("auth/VerifyEmail", inertia.Props{"email": user.Email})
18}
19 
20func Resend(r *web.Request) *web.Response {
21 user := r.User[models.User]()
22 if user.EmailVerifiedAt != nil {
23 return auth.RedirectIntended("/dashboard")
24 }
25 
26 if err := auth.SendVerificationLink(r, user); err != nil {
27 return web.Fail(err)
28 }
29 
30 inertia.Flash(r, "status", "We've sent you a new verification link.")
31 
32 return web.Back()
33}
1package verification
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/inertia"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Notice(r *web.Request) *web.Response {
12 user := r.User[models.User]()
13 if user.EmailVerifiedAt != nil {
14 return auth.RedirectIntended("/dashboard")
15 }
16 
17 return inertia.Render("auth/VerifyEmail", inertia.Props{"email": user.Email})
18}
19 
20func Resend(r *web.Request) *web.Response {
21 user := r.User[models.User]()
22 if user.EmailVerifiedAt != nil {
23 return auth.RedirectIntended("/dashboard")
24 }
25 
26 if err := auth.SendVerificationLink(r, user); err != nil {
27 return web.Fail(err)
28 }
29 
30 inertia.Flash(r, "status", "We've sent you a new verification link.")
31 
32 return web.Back()
33}

Inertia pages receive flashed messages in their flash field, so Resend flashes its status with inertia.Flash before it redirects.

Verifying the email

When the user opens the link, it runs the handler of your verification.verify route. Call auth.VerifyEmail there:

1func Verify(r *web.Request) *web.Response {
2 if _, err := auth.VerifyEmail[models.User](r); err != nil {
3 return web.Fail(err)
4 }
5 
6 inertia.Flash(r, "status", "Your email is verified.")
7 
8 return auth.RedirectIntended("/dashboard")
9}
1func Verify(r *web.Request) *web.Response {
2 if _, err := auth.VerifyEmail[models.User](r); err != nil {
3 return web.Fail(err)
4 }
5 
6 inertia.Flash(r, "status", "Your email is verified.")
7 
8 return auth.RedirectIntended("/dashboard")
9}

VerifyEmail checks that the link hasn't been changed or expired, and that Laravel sent it to the logged-in user at their current address. Then it sets the user's email_verified_at to now, and returns the user. A user who opens the same link twice gets the same result.

VerifyEmail turns invalid requests away in three cases:

  • A guest goes to the login page first, and RedirectIntended brings them back to the link once they log in.
  • A link that has expired or that someone changed gets a 403 that wraps urls.ErrExpired or urls.ErrInvalidSignature.
  • A link that Laravel sent to another user, or to an address the user no longer has, gets auth.ErrInvalidVerificationLink, a 403 that says "This verification link is invalid."

Rather than show a 403 error page for an expired or invalid link, you may check the error with errors.Is right inside the handler, and send the user back to the notice page with a status message:

1import (
2 "errors"
3 
4 "go.laravel.com/auth"
5 "go.laravel.com/inertia"
6 "go.laravel.com/urls"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12func Verify(r *web.Request) *web.Response {
13 _, err := auth.VerifyEmail[models.User](r)
14 switch {
15 case errors.Is(err, urls.ErrExpired), errors.Is(err, urls.ErrInvalidSignature),
16 errors.Is(err, auth.ErrInvalidVerificationLink):
17 inertia.Flash(
18 r,
19 "status",
20 "That verification link has expired or is invalid. Please request a new one.",
21 )
22 
23 return web.RedirectRoute("verification.notice")
24 case err != nil:
25 return web.Fail(err)
26 }
27 
28 inertia.Flash(r, "status", "Your email is verified.")
29 
30 return auth.RedirectIntended("/dashboard")
31}
1import (
2 "errors"
3 
4 "go.laravel.com/auth"
5 "go.laravel.com/inertia"
6 "go.laravel.com/urls"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12func Verify(r *web.Request) *web.Response {
13 _, err := auth.VerifyEmail[models.User](r)
14 switch {
15 case errors.Is(err, urls.ErrExpired), errors.Is(err, urls.ErrInvalidSignature),
16 errors.Is(err, auth.ErrInvalidVerificationLink):
17 inertia.Flash(
18 r,
19 "status",
20 "That verification link has expired or is invalid. Please request a new one.",
21 )
22 
23 return web.RedirectRoute("verification.notice")
24 case err != nil:
25 return web.Fail(err)
26 }
27 
28 inertia.Flash(r, "status", "Your email is verified.")
29 
30 return auth.RedirectIntended("/dashboard")
31}

You may also handle these errors for every route by rendering errors yourself.

Requiring a verified email

Some pages, such as billing, should wait until the user has verified their email. The auth.RequireVerifiedEmail middleware lets only those users through. Put it after Authenticate, since it needs a logged-in user:

1route.Middleware(auth.Authenticate{}, auth.RequireVerifiedEmail{}).Group(func(route *routing.Router) {
2 route.Get("/billing", billing.Show)
3})
1route.Middleware(auth.Authenticate{}, auth.RequireVerifiedEmail{}).Group(func(route *routing.Router) {
2 route.Get("/billing", billing.Show)
3})

RequireVerifiedEmail redirects an unverified user to your verification.notice page. Once they open the link, RedirectIntended in your Verify handler sends them back to the page they originally requested. A request that expects JSON gets a 403 instead.

To check whether a user has verified their email in your own code, check their EmailVerifiedAt field:

1if user.EmailVerifiedAt == nil {
2 // ...
3}
1if user.EmailVerifiedAt == nil {
2 // ...
3}

Changing a user's email

Whenever a user changes their email address, clear email_verified_at in the same update, and send a new verification link to the new address:

1package profile
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/db"
6 "go.laravel.com/model"
7 "go.laravel.com/validation"
8 "go.laravel.com/validation/rule"
9 "go.laravel.com/web"
10 
11 "app/models"
12)
13 
14type UpdateEmail struct {
15 Email string `json:"email" transform:"lowercase"`
16}
17 
18func (f *UpdateEmail) Rules(r *web.Request) (validation.Rules, error) {
19 return validation.For(f,
20 rule.Field(&f.Email,
21 rule.Required,
22 rule.Email,
23 model.Unique[models.User]().Ignore(r.User[models.User]()),
24 ),
25 ), nil
26}
27 
28func UpdateEmailAddress(r *web.Request) *web.Response {
29 form, err := r.Validate[UpdateEmail]()
30 if err != nil {
31 return web.Fail(err)
32 }
33 
34 user := r.User[models.User]()
35 if err := model.Update(r, user, db.Values{
36 "email": form.Email,
37 "email_verified_at": nil,
38 }); err != nil {
39 return web.Fail(err)
40 }
41 
42 if err := auth.SendVerificationLink(r, user); err != nil {
43 return web.Fail(err)
44 }
45 
46 return web.Back()
47}
1package profile
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/db"
6 "go.laravel.com/model"
7 "go.laravel.com/validation"
8 "go.laravel.com/validation/rule"
9 "go.laravel.com/web"
10 
11 "app/models"
12)
13 
14type UpdateEmail struct {
15 Email string `json:"email" transform:"lowercase"`
16}
17 
18func (f *UpdateEmail) Rules(r *web.Request) (validation.Rules, error) {
19 return validation.For(f,
20 rule.Field(&f.Email,
21 rule.Required,
22 rule.Email,
23 model.Unique[models.User]().Ignore(r.User[models.User]()),
24 ),
25 ), nil
26}
27 
28func UpdateEmailAddress(r *web.Request) *web.Response {
29 form, err := r.Validate[UpdateEmail]()
30 if err != nil {
31 return web.Fail(err)
32 }
33 
34 user := r.User[models.User]()
35 if err := model.Update(r, user, db.Values{
36 "email": form.Email,
37 "email_verified_at": nil,
38 }); err != nil {
39 return web.Fail(err)
40 }
41 
42 if err := auth.SendVerificationLink(r, user); err != nil {
43 return web.Fail(err)
44 }
45 
46 return web.Back()
47}

model.Update also sets the user's Email and EmailVerifiedAt fields, so SendVerificationLink sees an unverified user and sends the link to the new address. Any link sent to the previous address stops working immediately, because each link is hashed against the user's current email address.

Customizing the verification email

By default, Laravel sends verification links with the auth.VerificationEmail mailable, which uses the subject "Verify your email address" and renders with Laravel's mail components.

To change the email's wording without writing a mailable of your own, such as a line about what verifying unlocks, copy Laravel's auth::verify-email view into your application with vendor:publish:

1laravel vendor:publish auth verify-email
1laravel vendor:publish auth verify-email

The command writes resources/views/vendor/auth/verify-email.html. Edit that file to fit your brand, and Laravel renders your copy whenever it sends a verification email. The view receives the signed link as .URL and how many minutes the link works as .Minutes:

1{{template "mail::layout" .}}
2 
3{{define "content"}}
4<h1>Welcome to {{config.App.Name}}!</h1>
5<p>Confirm your email address to start your free trial.</p>
6{{template "mail::button" (dict "Label" "Confirm my email" "URL" .URL)}}
7<p>This link expires in {{.Minutes}} minutes.</p>
8{{end}}
1{{template "mail::layout" .}}
2 
3{{define "content"}}
4<h1>Welcome to {{config.App.Name}}!</h1>
5<p>Confirm your email address to start your free trial.</p>
6{{template "mail::button" (dict "Label" "Confirm my email" "URL" .URL)}}
7<p>This link expires in {{.Minutes}} minutes.</p>
8{{end}}

To send a mailable of your own, such as one with another subject, call auth.SendVerificationLinkWith wherever you would call SendVerificationLink. It takes a function that receives the user and their signed link. This VerifyYourEmail mailable greets the user by name, and renders resources/views/mails/verify-your-email.html:

1import (
2 "context"
3 
4 "go.laravel.com/auth"
5 "go.laravel.com/inertia"
6 "go.laravel.com/mail"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12type VerifyYourEmail struct {
13 Name string
14 URL string
15}
16 
17func (m VerifyYourEmail) Build() mail.Message {
18 return mail.Message{
19 Subject: "Confirm your email address",
20 View: "mails.verify-your-email",
21 Data: m,
22 }
23}
24 
25func Resend(r *web.Request) *web.Response {
26 user := r.User[models.User]()
27 if user.EmailVerifiedAt != nil {
28 return auth.RedirectIntended("/dashboard")
29 }
30 
31 err := auth.SendVerificationLinkWith(
32 r,
33 user,
34 func(ctx context.Context, user *models.User, link string) error {
35 return mail.To(user).Queue(ctx, VerifyYourEmail{Name: user.Name, URL: link})
36 },
37 )
38 if err != nil {
39 return web.Fail(err)
40 }
41 
42 inertia.Flash(r, "status", "We've sent you a new verification link.")
43 
44 return web.Back()
45}
1import (
2 "context"
3 
4 "go.laravel.com/auth"
5 "go.laravel.com/inertia"
6 "go.laravel.com/mail"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12type VerifyYourEmail struct {
13 Name string
14 URL string
15}
16 
17func (m VerifyYourEmail) Build() mail.Message {
18 return mail.Message{
19 Subject: "Confirm your email address",
20 View: "mails.verify-your-email",
21 Data: m,
22 }
23}
24 
25func Resend(r *web.Request) *web.Response {
26 user := r.User[models.User]()
27 if user.EmailVerifiedAt != nil {
28 return auth.RedirectIntended("/dashboard")
29 }
30 
31 err := auth.SendVerificationLinkWith(
32 r,
33 user,
34 func(ctx context.Context, user *models.User, link string) error {
35 return mail.To(user).Queue(ctx, VerifyYourEmail{Name: user.Name, URL: link})
36 },
37 )
38 if err != nil {
39 return web.Fail(err)
40 }
41 
42 inertia.Flash(r, "status", "We've sent you a new verification link.")
43 
44 return web.Back()
45}

Like SendVerificationLink, SendVerificationLinkWith calls your function only for a user who hasn't verified their email yet. To put the link in another email regardless, such as a welcome email, call auth.VerificationLink(r, user), which returns the link.

Testing

To test email verification, give your application a mail fake, read the signed URL from the queued auth.VerificationEmail, and visit it as the user:

1package feature_test
2 
3import (
4 "net/url"
5 "testing"
6 
7 "go.laravel.com/auth"
8 "go.laravel.com/mailtest"
9 
10 "app/database/factories"
11 "app/tests"
12)
13 
14func TestUsersCanVerifyTheirEmail(t *testing.T) {
15 client := tests.New(t)
16 emails := mailtest.New(client)
17 user := client.Create(factories.User.State(factories.Unverified))
18 
19 client.ActingAs(&user).Post("/email/verification-notification", nil)
20 
21 sent := emails.Queued[auth.VerificationEmail]()
22 if len(sent) != 1 {
23 t.Fatalf("queued %d verification emails, want one", len(sent))
24 }
25 link, _ := url.Parse(sent[0].Mailable.URL)
26 
27 client.ActingAs(&user).Get(link.RequestURI()).AssertRedirect("/dashboard")
28}
1package feature_test
2 
3import (
4 "net/url"
5 "testing"
6 
7 "go.laravel.com/auth"
8 "go.laravel.com/mailtest"
9 
10 "app/database/factories"
11 "app/tests"
12)
13 
14func TestUsersCanVerifyTheirEmail(t *testing.T) {
15 client := tests.New(t)
16 emails := mailtest.New(client)
17 user := client.Create(factories.User.State(factories.Unverified))
18 
19 client.ActingAs(&user).Post("/email/verification-notification", nil)
20 
21 sent := emails.Queued[auth.VerificationEmail]()
22 if len(sent) != 1 {
23 t.Fatalf("queued %d verification emails, want one", len(sent))
24 }
25 link, _ := url.Parse(sent[0].Mailable.URL)
26 
27 client.ActingAs(&user).Get(link.RequestURI()).AssertRedirect("/dashboard")
28}

The User factory in new applications creates users who have verified their email, so use client.Create(factories.User) for a verified user, and the factories.Unverified state when you test an unverified account.