By verifying the users' email, we can minimize the unwanted users on our application. In Laravel, we can easily implement this feature without even sweating a bit.
Make sure your mail setting is configured
For laravel/ui
or laravel/breeze
The first step is implementing the MustVerifyEmail
interface to the User model like this:
app\Models\User.php
:
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable implements MustVerifyEmail { ... // Too Long For This Post }
After that, assign the verified
middleware to any route you want. For example, I assigned it to the existing home
or dashboard
route:
routes\web.php
:
... // Laravel/UI Auth::routes(['verify' => true]); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home')->middleware(['auth','verified']); // Laravel/Breeze Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth', 'verified'])->name('dashboard'); ...
Now try to register a user. When it successfully registered, you will be redirected to this page because you aren't verified yet:
For laravel/fortify
or laravel/jetstream
Instead of implementing the MustVerifyEmail
interface to the User model, Fortify or Jetstream has its own configuration in config\fortify.php
file to enable the email verification feature:
... /* |-------------------------------------------------------------------------- | Features |-------------------------------------------------------------------------- | | Some of the Fortify features are optional. You may disable the features | by removing them from this array. You're free to only remove some of | these features or you can even remove all of these if you need to. | */ 'features' => [ ... Features::emailVerification(), ... ], ...
Then you should see a similar page in the jetstream app.
But if you use only Fortify, you have to manually add the view as resources\views\auth\verify-email.blade.php
and maybe the other required views as well. You can borrow from Breeze or Laravel/UI and It should be work fine.
That's for this useful feature of Laravel.
versions used:
Laravel Framework: 8.x
Top comments (0)