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
Forlaravel/ui
orlaravel/breeze
The first step is implementing theMustVerifyEmail
interface to the User model like this:
app\Models\User.php
:
<?phpnamespaceApp\Models;useIlluminate\Contracts\Auth\MustVerifyEmail;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Foundation\Auth\UserasAuthenticatable;useIlluminate\Notifications\Notifiable;classUserextendsAuthenticatableimplementsMustVerifyEmail{...// Too Long For This Post}
After that, assign theverified
middleware to any route you want. For example, I assigned it to the existinghome
ordashboard
route:
routes\web.php
:
...// Laravel/UIAuth::routes(['verify'=>true]);Route::get('/home',[App\Http\Controllers\HomeController::class,'index'])->name('home')->middleware(['auth','verified']);// Laravel/BreezeRoute::get('/dashboard',function(){returnview('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:
Forlaravel/fortify
orlaravel/jetstream
Instead of implementing theMustVerifyEmail
interface to the User model, Fortify or Jetstream has its own configuration inconfig\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 asresources\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)
For further actions, you may consider blocking this person and/orreporting abuse