Email Verification
- Introduction
- Setting up verification
- Sending verification links
- Verifying the email
- Requiring a verified email
- Changing a user's email
- Customizing the verification email
- Testing
Introduction
Many web applications require users to confirm their email address before accessing sensitive features or receiving transactional mail. Laravel can send a signed verification link to the user's inbox, validate it when opened, and protect routes with middleware, while leaving your application in charge of rendering the verification notice page.
Before getting started, configure authentication so users can sign in.
Setting up verification
To enable email verification, derive MustVerifyEmail on your User model. The derive reads the user's address from email and verification timestamp from email_verified_at. New applications include both columns on User and in its migration:
1use laravel::auth::{Authenticatable, MustVerifyEmail};2use laravel::model::model;3use laravel::time::Timestamp;45#[model]6#[derive(Authenticatable, MustVerifyEmail)]7pub struct User {8 pub id: i64,9 pub email: String,10 pub email_verified_at: Option<Timestamp>,11 // ...12}1use laravel::auth::{Authenticatable, MustVerifyEmail};2use laravel::model::model;3use laravel::time::Timestamp;45#[model]6#[derive(Authenticatable, MustVerifyEmail)]7pub struct User {8 pub id: i64,9 pub email: String,10 pub email_verified_at: Option<Timestamp>,11 // ...12}
Laravel sends verification links using the mail system by passing your user to mail::to(&user). To make User usable as a recipient, implement From<&User> for Address in src/models/user.rs (see Recipients):
1use laravel::mail::Address;23impl From<&User> for Address {4 fn from(user: &User) -> Self {5 Address::new(&user.email).with_name(&user.name)6 }7}1use laravel::mail::Address;23impl From<&User> for Address {4 fn from(user: &User) -> Self {5 Address::new(&user.email).with_name(&user.name)6 }7}
Email verification requires three routes behind Authenticate: a notice page prompting the user to check their inbox, a route to resend the verification email, and the route that handles clicking the verification link. Throttle the resend and verify routes with separate buckets to prevent inbox flooding and brute-force attempts while allowing users who request a new link to open it immediately:
1use laravel::auth::Authenticate;2use laravel::http::middleware::Throttle;34route.middleware(Authenticate).group(|route| {5 route.get("/verify-email", verification::notice);67 route8 .post("/verify-email", verification::resend)9 .middleware(Throttle::per_minute(6).bucket("verification-resend"));1011 route12 .get("/verify-email/{id}/{hash}", verification::verify)13 .middleware(Throttle::per_minute(6).bucket("verification-verify"));14});1use laravel::auth::Authenticate;2use laravel::http::middleware::Throttle;34route.middleware(Authenticate).group(|route| {5 route.get("/verify-email", verification::notice);67 route8 .post("/verify-email", verification::resend)9 .middleware(Throttle::per_minute(6).bucket("verification-resend"));1011 route12 .get("/verify-email/{id}/{hash}", verification::verify)13 .middleware(Throttle::per_minute(6).bucket("verification-verify"));14});
Each verification link carries the user's ID and a hash of their email address in the {id} and {hash} parameters, so the verification route needs both. To let Laravel locate the notice page and verification route, mark those two handlers with #[laravel::auth::page(..)]:
1#[laravel::auth::page(verification_notice)]2pub async fn notice(user: Authenticated<User>) -> laravel::Result<Response> {3 // ...4}56#[laravel::auth::page(verify_email)]7pub async fn verify(verification: EmailVerification<User>) -> laravel::Result<Redirect> {8 // ...9}1#[laravel::auth::page(verification_notice)]2pub async fn notice(user: Authenticated<User>) -> laravel::Result<Response> {3 // ...4}56#[laravel::auth::page(verify_email)]7pub async fn verify(verification: EmailVerification<User>) -> laravel::Result<Redirect> {8 // ...9}
Sending verification links
Send the first link as soon as a user signs up. Take EmailVerification<User> as a handler argument, and pass the new user to send_link. This sign-up handler creates the user, logs them in, and sends the link:
1use laravel::auth::{Auth, EmailVerification};2use laravel::hash::Password;3use laravel::model::create;4use laravel::prelude::*;56#[laravel::input]7#[validate(anyone)]8pub struct SignUp {9 #[validate(required, max_length(255))]10 name: String,11 #[transform(lowercase)]12 #[validate(required, email, unique(User::email))]13 email: String,14 #[validate(required, password, confirmed)]15 password: Password,16}1718pub async fn sign_up(19 auth: Auth<User>,20 verification: EmailVerification<User>,21 Valid(form): Valid<SignUp>,22) -> laravel::Result<Redirect> {23 let user = create!(User {24 name: &form.name,25 email: &form.email,26 password: &form.password,27 })28 .await?;2930 auth.login(&user).await?;3132 verification.send_link(&user).await?;3334 Ok(redirect!(dashboard::show))35}1use laravel::auth::{Auth, EmailVerification};2use laravel::hash::Password;3use laravel::model::create;4use laravel::prelude::*;56#[laravel::input]7#[validate(anyone)]8pub struct SignUp {9 #[validate(required, max_length(255))]10 name: String,11 #[transform(lowercase)]12 #[validate(required, email, unique(User::email))]13 email: String,14 #[validate(required, password, confirmed)]15 password: Password,16}1718pub async fn sign_up(19 auth: Auth<User>,20 verification: EmailVerification<User>,21 Valid(form): Valid<SignUp>,22) -> laravel::Result<Redirect> {23 let user = create!(User {24 name: &form.name,25 email: &form.email,26 password: &form.password,27 })28 .await?;2930 auth.login(&user).await?;3132 verification.send_link(&user).await?;3334 Ok(redirect!(dashboard::show))35}
send_link queues a VerificationEmail containing a signed link valid for 60 minutes. 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:
1use laravel::auth::{EmailVerification, MustVerifyEmail};2use laravel::inertia::{self, props};3use laravel::prelude::*;45#[laravel::auth::page(verification_notice)]6pub async fn notice(user: Authenticated<User>) -> Response {7 if user.has_verified_email() {8 return Redirect::intended(dashboard::show, ()).into_response();9 }1011 inertia::render("auth/VerifyEmail", props! { "email" => &user.email }).into_response()12}1314pub async fn resend(15 user: Authenticated<User>,16 verification: EmailVerification<User>,17) -> laravel::Result<Redirect> {18 if user.has_verified_email() {19 return Ok(Redirect::intended(dashboard::show, ()));20 }2122 verification.send_link(&user).await?;2324 Ok(Redirect::back().with("status", "We've sent you a new verification link."))25}1use laravel::auth::{EmailVerification, MustVerifyEmail};2use laravel::inertia::{self, props};3use laravel::prelude::*;45#[laravel::auth::page(verification_notice)]6pub async fn notice(user: Authenticated<User>) -> Response {7 if user.has_verified_email() {8 return Redirect::intended(dashboard::show, ()).into_response();9 }1011 inertia::render("auth/VerifyEmail", props! { "email" => &user.email }).into_response()12}1314pub async fn resend(15 user: Authenticated<User>,16 verification: EmailVerification<User>,17) -> laravel::Result<Redirect> {18 if user.has_verified_email() {19 return Ok(Redirect::intended(dashboard::show, ()));20 }2122 verification.send_link(&user).await?;2324 Ok(Redirect::back().with("status", "We've sent you a new verification link."))25}
The notice returns a Response, so that one branch can redirect and the other can render the page.
Verifying the email
When the user opens the link, it runs the handler marked #[laravel::auth::page(verify_email)]. Call verify there:
1use laravel::auth::EmailVerification;2use laravel::prelude::*;34#[laravel::auth::page(verify_email)]5pub async fn verify(verification: EmailVerification<User>) -> laravel::Result<Redirect> {6 verification.verify().await?;78 Ok(Redirect::intended(dashboard::show, ()).with("status", "Your email is verified."))9}1use laravel::auth::EmailVerification;2use laravel::prelude::*;34#[laravel::auth::page(verify_email)]5pub async fn verify(verification: EmailVerification<User>) -> laravel::Result<Redirect> {6 verification.verify().await?;78 Ok(Redirect::intended(dashboard::show, ()).with("status", "Your email is verified."))9}
verify checks that the link hasn't been changed or expired, and that it was sent 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.
verify rejects invalid requests in three cases:
- Guests are redirected to the login page; after signing in,
Redirect::intendedreturns them to the verification link. - Expired or tampered links return a
403withInvalidSignature. - Links belonging to another user or an outdated email address return a
403withInvalidVerificationLink.
Rather than showing a 403 error page for an expired or invalid link, you can catch InvalidSignature and InvalidVerificationLink right inside the handler and redirect the user back to the verification notice page with a status message:
1use laravel::auth::{EmailVerification, InvalidVerificationLink};2use laravel::prelude::*;3use laravel::url::InvalidSignature;45#[laravel::auth::page(verify_email)]6pub async fn verify(verification: EmailVerification<User>) -> laravel::Result<Redirect> {7 if let Err(error) = verification.verify().await {8 if error.is::<InvalidSignature>() || error.is::<InvalidVerificationLink>() {9 return Ok(redirect!(notice).with(10 "status",11 "That verification link has expired or is invalid. Please request a new one.",12 ));13 }1415 return Err(error);16 }1718 Ok(Redirect::intended(dashboard::show, ()).with("status", "Your email is verified."))19}1use laravel::auth::{EmailVerification, InvalidVerificationLink};2use laravel::prelude::*;3use laravel::url::InvalidSignature;45#[laravel::auth::page(verify_email)]6pub async fn verify(verification: EmailVerification<User>) -> laravel::Result<Redirect> {7 if let Err(error) = verification.verify().await {8 if error.is::<InvalidSignature>() || error.is::<InvalidVerificationLink>() {9 return Ok(redirect!(notice).with(10 "status",11 "That verification link has expired or is invalid. Please request a new one.",12 ));13 }1415 return Err(error);16 }1718 Ok(Redirect::intended(dashboard::show, ()).with("status", "Your email is verified."))19}
You may also handle either error globally by registering a custom error renderer.
Requiring a verified email
Some pages, such as billing, should wait until the user has verified their email. The RequireVerifiedEmail middleware lets only those users through. Put it after Authenticate:
1use laravel::auth::{Authenticate, RequireVerifiedEmail};23route.middleware(Authenticate).middleware(RequireVerifiedEmail).group(|route| {4 route.get("/billing", billing::show);5});1use laravel::auth::{Authenticate, RequireVerifiedEmail};23route.middleware(Authenticate).middleware(RequireVerifiedEmail).group(|route| {4 route.get("/billing", billing::show);5});
RequireVerifiedEmail redirects unverified users to your notice page. Once they open the link, Redirect::intended in your verify handler sends them back to the page they originally requested. Requests expecting JSON receive a 403 instead.
If User doesn't derive MustVerifyEmail, RequireVerifiedEmail allows every logged-in user through. To check verification status directly in your own code, call user.has_verified_email():
1use laravel::auth::MustVerifyEmail;23if !user.has_verified_email() {4 // ...5}1use laravel::auth::MustVerifyEmail;23if !user.has_verified_email() {4 // ...5}
Changing a user's email
Whenever a user updates their email address, clear email_verified_at in the same update and send a new verification link to the updated address:
1use laravel::auth::EmailVerification;2use laravel::model::update;3use laravel::prelude::*;45#[laravel::input]6#[validate(authenticated)]7pub struct UpdateEmail {8 #[transform(lowercase)]9 #[validate(required, email)]10 email: String,11}1213pub async fn update_email(14 Authenticated(mut user): Authenticated<User>,15 verification: EmailVerification<User>,16 Valid(form): Valid<UpdateEmail>,17) -> laravel::Result<Redirect> {18 update!(user { email: &form.email, email_verified_at: None }).await?;1920 verification.send_link(&user).await?;2122 Ok(Redirect::back())23}1use laravel::auth::EmailVerification;2use laravel::model::update;3use laravel::prelude::*;45#[laravel::input]6#[validate(authenticated)]7pub struct UpdateEmail {8 #[transform(lowercase)]9 #[validate(required, email)]10 email: String,11}1213pub async fn update_email(14 Authenticated(mut user): Authenticated<User>,15 verification: EmailVerification<User>,16 Valid(form): Valid<UpdateEmail>,17) -> laravel::Result<Redirect> {18 update!(user { email: &form.email, email_verified_at: None }).await?;1920 verification.send_link(&user).await?;2122 Ok(Redirect::back())23}
Any verification link sent to the previous address becomes invalid immediately because each link is hashed against the user's current email address.
Customizing the verification email
By default, Laravel sends verification links using the built-in laravel::auth::VerificationEmail mailable, which uses the subject "Verify your email address" and renders with Laravel's mail components.
To customize the email's wording or layout without writing a custom mailable, copy resources/views/auth/verify-email.html to resources/views/vendor/laravel/auth/verify-email.html in your application and edit it to fit your brand. The template receives url for the signed verification link and minutes for the expiration window.
To send a mailable of your own, build the link with url, and queue your mailable wherever you would call send_link. This VerifyYourEmail mailable greets the user by name, and renders resources/views/mail/verify-your-email.html:
1use laravel::auth::{EmailVerification, MustVerifyEmail};2use laravel::mail::{self, Mailable};3use laravel::prelude::*;45#[derive(Mailable)]6#[mail(subject = "Verify your email address")]7pub struct VerifyYourEmail {8 pub name: String,9 pub url: String,10}1112pub async fn resend(13 user: Authenticated<User>,14 verification: EmailVerification<User>,15) -> laravel::Result<Redirect> {16 if user.has_verified_email() {17 return Ok(Redirect::intended(dashboard::show, ()));18 }1920 let url = verification.url(&user)?;2122 mail::to(&user).queue(VerifyYourEmail { name: user.name.clone(), url }).await?;2324 Ok(Redirect::back().with("status", "We've sent you a new verification link."))25}1use laravel::auth::{EmailVerification, MustVerifyEmail};2use laravel::mail::{self, Mailable};3use laravel::prelude::*;45#[derive(Mailable)]6#[mail(subject = "Verify your email address")]7pub struct VerifyYourEmail {8 pub name: String,9 pub url: String,10}1112pub async fn resend(13 user: Authenticated<User>,14 verification: EmailVerification<User>,15) -> laravel::Result<Redirect> {16 if user.has_verified_email() {17 return Ok(Redirect::intended(dashboard::show, ()));18 }1920 let url = verification.url(&user)?;2122 mail::to(&user).queue(VerifyYourEmail { name: user.name.clone(), url }).await?;2324 Ok(Redirect::back().with("status", "We've sent you a new verification link."))25}
Unlike send_link, your own email goes out even to a user who has already verified their email, so check first, as this handler does.
Testing
To test email verification, fake mail, read the signed url from the queued VerificationEmail, and visit it as the user:
1use app::models::User;2use laravel::auth::VerificationEmail;3use laravel::mail;4use laravel::testing::prelude::*;56#[laravel::test]7async fn users_can_verify_their_email(app: Application) -> laravel::Result<()> {8 let mail = mail::fake();9 let user = User::factory().unverified().create().await?;1011 app.post("/verify-email").acting_as(&user).await.assert_redirect();1213 let emails = mail.queued::<VerificationEmail>();14 let link = &emails[0].mailable().url;1516 app.get(link)17 .acting_as(&user)18 .await19 .assert_redirect_to(route!(dashboard::show)?);2021 Ok(())22}1use app::models::User;2use laravel::auth::VerificationEmail;3use laravel::mail;4use laravel::testing::prelude::*;56#[laravel::test]7async fn users_can_verify_their_email(app: Application) -> laravel::Result<()> {8 let mail = mail::fake();9 let user = User::factory().unverified().create().await?;1011 app.post("/verify-email").acting_as(&user).await.assert_redirect();1213 let emails = mail.queued::<VerificationEmail>();14 let link = &emails[0].mailable().url;1516 app.get(link)17 .acting_as(&user)18 .await19 .assert_redirect_to(route!(dashboard::show)?);2021 Ok(())22}
The default User factory creates verified users out of the box, so use User::factory().create().await? for verified users and .unverified() when testing unverified accounts.