Email Verification In Laravel 9
Laravel provides a built-in email verification feature so here we will discuss how to enable this feature in our application. Follow some easy steps to enable this feature in laravel application.
STEP 1: Create Laravel App
laravel new laravel-email-varification
STEP 2: Go to the app directory
cd laravel-email-varificationSTEP 3: Install Laravel Starter Kits
composer require laravel/ui
php artisan ui bootstrap --auth
npm install
npm run build
STEP 4: Changes In User Model
go to App\Models\User and uncomment or add theMustVerifyEmailcontract.
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;use Laravel\Sanctum\HasApiTokens;class User extends Authenticatable implements MustVerifyEmail{use HasApiTokens, HasFactory, Notifiable;}
STEP 5: Defined Routes In web.php file
Add two illuminate request
use Illuminate\Foundation\Auth\EmailVerificationRequest;use Illuminate\Http\Request;
Add Three Routes
//First Route - return auth verify view.Route::get('/email/verify', function () {return view('auth.verify');})->middleware('auth')->name('verification.notice');//Second Route - generated and send email verification link.Route::post('/email/verification-notification', function (Request $request) {$request->user()->sendEmailVerificationNotification();return back()->with('message', 'Verification link sent!');})->middleware(['auth', 'throttle:6,1'])->name('verification.resend');//Third Route - update the email_verified_at column in user table.Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {$request->fulfill();return redirect('/home');})->middleware(['auth', 'signed'])->name('verification.verify');
STEP 6: Now protect your routes or controllers
add verified middleware in your route or controller which routes or controllers, you want to access only verified user.
Protect Routes.
Route::get('/home', [HomeController::class, 'index'])->middleware(['auth', 'verified']);
Protect Controller
public function __construct(){$this->middleware([ 'auth','verified']);}
namespace App\Http\Controllers;use Illuminate\Http\Request;class HomeController extends Controller{public function __construct(){$this->middleware([ 'auth','verified']);}public function index(){return view('home');}}
STEP 7: Migrate database
php artisan migrate
STEP 8: Run and test login, register, and verify functionality.
Run your app using the artisan command:
php artisan serve
OUTPUT


