Email verification in laravel 10; In this tutorial, we will show you how to implement email verification system in laravel 10 application.
Email Verification in Laravel 10
Steps to implement email verification in laravel 10 web apps:
- Step 1: Install Laravel 10
- Step 2: Setup Mail Configuration
- Step 3: Create “users_verify” table using Migration
- Step 4: Create Update Model
- Step 5: Create Route
- Step 6: Update Auth Controller
- Step 7: Create Blade File
- Step 8: Create Middleware
- Step 9: Start Development Server
Step 1: Install Laravel 10
First of all, open your terminal or cmd and execute the following command into it to install laravel 10 app into your system:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Setup Mail Configuration
Next, visit your downloaded Laravel 10 root directory. Then open your .env file and update email configuration details; as shown below:
Step 3: Create “users_verify” table using Migration
Execute the following command on your terminal to create users_verify table into your database using laravel migration:
php artisan make:model UserVerify -m
Then visit the database/migration directory and open create_users_verify_table.php file and add the following code into your file; as shown below:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class UsersVerify extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users_verify', function (Blueprint $table) {
$table->integer('user_id');
$table->string('token');
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_email_verified')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
Step 4: Update Model
Now open these two user.php and UserVerify.php models files. Then update the following code into these files; as shown below:
Update the following code into app/Models/User.php file; as shown below:
<?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
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'is_email_verified'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Next, Update the following code into app/Models/UserVerify.php file; as shown below:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserVerify extends Model
{
use HasFactory;
public $table = "users_verify";
/**
* Write code on Method
*
* @return response()
*/
protected $fillable = [
'user_id',
'token',
];
/**
* Write code on Method
*
* @return response()
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
Step 5: Create Route
Visit routes directory and open web.php file and create a custom route for email verification; as shown below:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\AuthController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('login', [AuthController::class, 'index'])->name('login');
Route::post('post-login', [AuthController::class, 'postLogin'])->name('login.post');
Route::get('registration', [AuthController::class, 'registration'])->name('register');
Route::post('post-registration', [AuthController::class, 'postRegistration'])->name('register.post');
Route::get('logout', [AuthController::class, 'logout'])->name('logout');
/* New Added Routes */
Route::get('dashboard', [AuthController::class, 'dashboard'])->middleware(['auth', 'is_verify_email']);
Route::get('account/verify/{token}', [AuthController::class, 'verifyAccount'])->name('user.verify');
Step 6: Update Auth Controller
Visit app/Http/Controllers/Auth/ directory and open your auth controller (in our controller name is AuthController.php) file and update the following methods into it:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
use App\Models\User;
use App\Models\UserVerify;
use Hash;
use Illuminate\Support\Str;
use Mail;
class AuthController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
return view('auth.login');
}
/**
* Write code on Method
*
* @return response()
*/
public function registration()
{
return view('auth.registration');
}
/**
* Write code on Method
*
* @return response()
*/
public function postLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard')
->withSuccess('You have Successfully loggedin');
}
return redirect("login")->withSuccess('Oppes! You have entered invalid credentials');
}
/**
* Write code on Method
*
* @return response()
*/
public function postRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$createUser = $this->create($data);
$token = Str::random(64);
UserVerify::create([
'user_id' => $createUser->id,
'token' => $token
]);
Mail::send('email.emailVerificationEmail', ['token' => $token], function($message) use($request){
$message->to($request->email);
$message->subject('Email Verification Mail');
});
return redirect("dashboard")->withSuccess('Great! You have Successfully loggedin');
}
/**
* Write code on Method
*
* @return response()
*/
public function dashboard()
{
if(Auth::check()){
return view('dashboard');
}
return redirect("login")->withSuccess('Opps! You do not have access');
}
/**
* Write code on Method
*
* @return response()
*/
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
/**
* Write code on Method
*
* @return response()
*/
public function logout() {
Session::flush();
Auth::logout();
return Redirect('login');
}
/**
* Write code on Method
*
* @return response()
*/
public function verifyAccount($token)
{
$verifyUser = UserVerify::where('token', $token)->first();
$message = 'Sorry your email cannot be identified.';
if(!is_null($verifyUser) ){
$user = $verifyUser->user;
if(!$user->is_email_verified) {
$verifyUser->user->is_email_verified = 1;
$verifyUser->user->save();
$message = "Your e-mail is verified. You can now login.";
} else {
$message = "Your e-mail is already verified. You can now login.";
}
}
return redirect()->route('login')->with('message', $message);
}
}
Step 7: Create Blade File
Visit resources/views/emails/ directory and create emailVerificationEmail.blade.php file. Then update the following code into it;
<h1>Email Verification Mail</h1>
Please verify your email with bellow link:
<a href="{{ route('user.verify', $token) }}">Verify Email</a>
Step 8: Create Middleware
Execute the following command into your terminal to create middleware file:
php artisan make:middleware IsVerifyEmail
Then visit app/Http/Middleware/ directory and open IsVerifyEmail.php file; as shown below:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class IsVerifyEmail
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (!Auth::user()->is_email_verified) {
auth()->logout();
return redirect()->route('login')
->with('message', 'You need to confirm your account. We have sent you an activation code, please check your email.');
}
return $next($request);
}
}
Then register the middleware in kernal.php file; so visit app/Http/ directory and open Kernel.php file and update the following code into it:
protected $routeMiddleware = [
....
'is_verify_email' => \App\Http\Middleware\IsVerifyEmail::class,
];
Step 9: Start Development Server
Execute the following command on the terminal to start the development server:
php artisan serve
Then open your browser and hit the following url into it:
localhost:8000/register
Conclusion
Congratulations! You have learned how to implement an email verification system in laravel 10 application.