Docs / Security / Email Verification
Email Verification
Introduction
Many web applications require users to verify their email addresses before using the application. Rather than forcing you to re-implement this feature by hand for each application you create, laraflare provides convenient built-in services for sending and verifying email verification requests.
Note
Want to get started fast? A fresh laraflare application's skeleton already scaffolds your entire authentication system, including email verification support. See the starter kits.
Model Preparation
Before getting started, verify that your app/Models/User model opts in to email verification with the MustVerifyEmail mixin:
import { Authenticatable, MustVerifyEmail, Notifiable } from '@laraflare/framework';
export class User extends MustVerifyEmail(Notifiable(Authenticatable)) {
// ...
}
Once this mixin has been applied to your model, newly registered users will automatically be sent an email containing an email verification link. This happens seamlessly because laraflare automatically registers the SendEmailVerificationNotification listener for the Registered event.
If you are manually implementing registration within your application instead of using a starter kit, you should ensure that you are dispatching the Registered event after a user's registration is successful:
import { Registered, event } from '@laraflare/framework';
await event(new Registered(user));
Database Preparation
Next, your users table must contain an email_verified_at column to store the date and time that the user's email address was verified. Typically, this is included in laraflare's default create_users_table database migration.
Routing
To properly implement email verification, three routes will need to be defined. First, a route will be needed to display a notice to the user that they should click the email verification link in the verification email that laraflare sent them after registration.
Second, a route will be needed to handle requests generated when the user clicks the email verification link in the email.
Third, a route will be needed to resend a verification link if the user accidentally loses the first verification link.
The Email Verification Notice
As mentioned previously, a route should be defined that will show a screen instructing the user to click the email verification link that was emailed to them by laraflare after registration. This screen will be displayed to users when they try to access other parts of the application without verifying their email address first. Remember, the link is automatically emailed to the user as long as your app/Models/User model uses the MustVerifyEmail mixin:
Route.get('/email/verify', () => ({})).middleware('auth').name('verification.notice');
The route that shows the email verification notice should be named verification.notice. It is important that the route is assigned this exact name since the verified middleware included with laraflare will automatically redirect to this route name if a user has not verified their email address.
Note
When manually implementing email verification, you are required to write the verification notice screen yourself; screens are Vue components in
resources/js. If you would like scaffolding that includes all necessary authentication and verification screens, check out the starter kits.
The Email Verification Handler
Next, we need to define a route that will handle requests generated when the user clicks the email verification link that was emailed to them. This route should be named verification.verify and be assigned the auth and signed middlewares:
import { EmailVerificationRequest, redirect, Route } from '@laraflare/framework';
Route.get('/email/verify/{id}/{hash}', async (request: EmailVerificationRequest) => {
await request.fulfill();
return redirect('/home');
}).middleware(['auth', 'signed']).name('verification.verify');
Before moving on, let's take a closer look at this route. First, you'll notice we are using an EmailVerificationRequest request type instead of the typical Request instance. The EmailVerificationRequest is a form request that is included with laraflare. This request will automatically take care of validating the request's id and hash parameters.
Next, we can proceed directly to calling the fulfill method on the request. This method will call the markEmailAsVerified method on the authenticated user and dispatch the Verified event. The markEmailAsVerified method is available to the default app/Models/User model via the MustVerifyEmail mixin. Once the user's email address has been verified, you may redirect them wherever you wish.
Resending the Verification Email
Sometimes a user may misplace or accidentally delete the email address verification email. To accommodate this, you may wish to define a route to allow the user to request that the verification email be resent. You may then make a request to this route by placing a simple form submission button within your verification notice screen:
import { back, Route, type Request } from '@laraflare/framework';
Route.post('/email/verification-notification', async (request: Request) => {
await request.user().sendEmailVerificationNotification();
return back().with('message', 'Verification link sent!');
}).middleware(['auth', 'throttle:6,1']).name('verification.send');
Protecting Routes
Route middleware may be used to only allow verified users to access a given route. laraflare includes a verified middleware alias, which is an alias for the EnsureEmailIsVerified middleware class. Since this alias is already automatically registered by laraflare, all you need to do is attach the verified middleware to a route definition. Typically, this middleware is paired with the auth middleware:
Route.get('/profile', () => {
// Only verified users may access this route...
}).middleware(['auth', 'verified']);
If an unverified user attempts to access a route that has been assigned this middleware, they will automatically be redirected to the verification.notice named route.
Customization
Verification Email Customization
Although the default email verification notification should satisfy the requirements of most applications, laraflare allows you to customize how the email verification mail message is constructed.
To get started, pass a closure to the toMailUsing method provided by the VerifyEmail notification. The closure will receive the notifiable model instance that is receiving the notification as well as the signed email verification URL that the user must visit to verify their email address. The closure should return an instance of MailMessage. Typically, you should call the toMailUsing method from the boot method of your application's AppServiceProvider class:
import { MailMessage, ServiceProvider, VerifyEmail } from '@laraflare/framework';
export class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*/
override boot(): void {
// ...
VerifyEmail.toMailUsing((notifiable, url) => {
return new MailMessage()
.subject('Verify Email Address')
.line('Click the button below to verify your email address.')
.action('Verify Email Address', url);
});
}
}
Note
To learn more about mail notifications, please consult the mail notification documentation.
Events
When using the starter kits, laraflare dispatches a Verified event during the email verification process. If you are manually handling email verification for your application, you may wish to manually dispatch these events after verification is completed.