Laravel/UI: Implement Email Verification
In Laravel applications using the laravel/ui
(link) package for authentication, the feature for verifying an email address after registration is built-in but is not enforced by default. To implement email verification, follow the steps below:
1. Implement MustVerifyEmail Interface
Ensure that your User
model implements the MustVerifyEmail
interface, which will enforce the user to verify their email.
use Illuminate\Contracts\Auth\MustVerifyEmail;
class User extends Authenticatable implements MustVerifyEmail
{
// ...
}
2. Use the Email Verification Middleware
In your routes/web.php
file, make sure to use the auth
and verified
middleware on routes that require a verified email address.
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () {
// Only verified users may access this route...
})->middleware(['auth', 'verified']);
3. Migrate Changes to Database
Ensure your users
table has an email_verified_at
column to store the timestamp when the user verified their email. If you don’t have it, you may need to create a migration to add this column.
php artisan make:migration add_email_verified_at_to_users_table --table=users
In the generated migration file, you might add something like this:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->timestamp('email_verified_at')->nullable()->after('email');
});
}
Then run the migration:
php artisan migrate
4. Email Verification Notification
Laravel uses notifications to send the email verification link. Ensure that your User
model uses the Notifiable
trait.
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
// ...
}
Customizing Behavior
- Customizing Verification Email: You may customize the verification email by modifying the
toMail
method on theVerifyEmail
notification. - Redirecting After Verification: If you want to customize the redirect after the email is verified, you may define a
redirectTo
method or property on theEmailVerificationController
.
protected function redirectTo()
{
// Your redirect logic here...
return '/home';
}
Optional Email Verification
If you want to make email verification optional:
- Custom Middleware: Instead of using the built-in
verified
middleware, you could create a custom middleware that checks if the user has verified their email and acts accordingly (e.g., showing a persistent reminder to verify the email). - User Settings: Add an option in the user’s settings that allows them to toggle whether they want to verify their email. Be mindful of how this affects your app’s security and communication.
- Conditional Routes: You could add conditional logic to your routes or controllers to handle non-verified users distinctly.