How to Create Email Verification in Laravel 8 with Gmail (ok)

https://codelapan.com/post/how-to-create-email-verification-in-laravel-8-with-gmail

Đường dẫn để gửi lại xác thực trông giống như này https://lva3.com/email/verify Ví dụ đã hoàn thành :)

php artisan ui bootstrap --auth

C:\xampp\htdocs\test\routes\web.php

<?php
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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('/', function () {
  return view('welcome');
});
Auth::routes(['verify' => true]);
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home')->middleware('verified');

C:\xampp\htdocs\test\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;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable implements MustVerifyEmail {
  use HasApiTokens, HasFactory, Notifiable;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
    'name',
    'email',
    'password',
  ];
  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];
  /**
   * The attributes that should be cast.
   *
   * @var array<string, string>
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
}

C:\xampp\htdocs\test\app\Http\Controllers\HomeController.php

<?php
namespace App\Http\Controllers;
class HomeController extends Controller {
  /**
   * Create a new controller instance.
   *
   * @return void
   */
  public function __construct() {
    $this->middleware(['auth', 'verified']);
  }
  /**
   * Show the application dashboard.
   *
   * @return \Illuminate\Contracts\Support\Renderable
   */
  public function index() {
    return view('home');
  }
}

How to Create Email Verification in Laravel 8 with Gmail

Laravel Email Verification - If previously we have shared an article that discusses how to make account verification with a phone number, then on this occasion we will share an article that is almost the same but in different media. In this article, we will try how to make account verification with email or maybe better known as laravel email verification.

Previously, we had to know what the purpose of making email verification was in this project made with Laravel 8. So, making account verification or email verification will prevent users from entering or registering fake emails when registering.

For example, if there is a website that requires users to register but does not include account verification or email verification, the user can just enter fake emails such as sdsd@dds.dsfds to be able to go directly to the protected page (requires user login). It's different if the website requires that every user who registers or registers must verify the account first, it will certainly minimize users who register with fake data or emails.

Table of Contents

Setup Gmail Account

Because we will make email verification or account verification with email in laravel that uses Google mail service as a mail host, so we need to set up the gmail account.

Link: https://myaccount.google.com/u/1/security

Make sure the gmail account that will be used, in the Less secure application access section is active or can be seen as shown above (Sorry, in image above, i use google account with bahasa Indonesia).

Start Coding

Alright, let's just start the experiment of making email verification in laravel 8 with gmail. In this experiment we will start from 0 that is from starting to install a new laravel project until we successfully verify the email. Here are the steps:

Step 1: Install laravel 8

The first step is to install a new laravel project. Here we install it using composer. Open a terminal, go to the directory where we want to put the project folder. then run the command as below.

composer create-project laravel/laravel emailverify

Copy

With the above command, we will install a new laravel project which will be named emailverify.

Step 2: Install laravel ui package

We will use the laravel ui package to create the auth feature, and therefore we need to install the laravel ui package in our project. To install it, you can go to the project directory that we just installed with the cd emailverify command then run the command below.

composer require laravel/ui

Copy

After that, we need to install the ui using bootstrap to do authentication. Run the command below to install the bootstrap ui in the project.

php artisan ui bootstrap --auth

Copy

wait until the process is complete. If you have run the command

npm install && npm run dev

Copy

Wait for it to finish. If there is a "Finished, Please run mix again" message, run the command npm install && npm run dev again.

Step 3: Create database

To accommodate user data, we need to create a new database. For that please create a database first in xampp, laragon or others. In this experiment, I created a new database with the name laravel.

Step 4: Edit .env

Next, edit some records in the .env file. There are several records that we need to adjust, including DB_DATABASE. in DB_DATABASE enter the name of the new database that was created in step number 3. Then adjust it to the record below.

MAIL_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
MAIL_USERNAME=email@gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=email@gmail.com
MAIL_FROM_NAME="Your Name"

Copy

Here we will use smtp as the mailer, then for the host and port we use smtp.googlemail.com and 587, for encryption we can use tls. In the MAIL_USERNAME, MAIL_PASSWORD, MAIL_FROM_ADDRESS and MAIL_FROM_NAME records, please adjust them to your gmail account.

So overall, the .env file will be like below.

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:m5S1Xbfrx8FIeBbl5y8gdEptmMBOI/qRVcPszWbsi2w=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
MAIL_USERNAME=email@gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=email@gmail.com
MAIL_FROM_NAME="Bisabos"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Copy

Step 5: Migrate

To migrate the tables that have been created with migration to the database that has been created, we can run the php artisan migrate command.

Step 6: Setup Route

To enable the verification feature, we need to define it in the web.php file in the routes folder.

find code

Auth::routes();

Copy

Then, change into

Auth::routes(['verify' => true]);

Copy

Step 7: Edit Models/User.php

In the Models/User.php file add implements MustVerifyEmail, so the overall Models/User.php file will be as 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 implements MustVerifyEmail
{
    use HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
    /**
     * 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',
    ];
}

Copy

Step 8: Setup middleware

To provide protection on a page, we can use middleware. As in this experiment, we will protect the home page so that it cannot be accessed before the user verifies the email used when registering. Manage middleware can be placed in the controller or in the route.

Example of middleware in controller, we can add function as below in HomeController.php

public function __construct()
    {
        $this->middleware(['auth','verified']);
    }

Copy

Overall, the code contained in the HomeController.php file will be as below.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth','verified']);
    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }
}

Copy

Or you can also put the middleware in the route as below.

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home')->middleware('verified');

Copy

We are free to choose whether we want to use the middleware in the controller or route.

FINISHED.

Testing

Now comes the testing stage. To try it, please run the project with php artisan serve or if you use valet please access it with namaproject.test.

Then we will not be directly directed to the home page but to the email verify page first. To be able to proceed to the home page, we must verify our email first. Please check the inbox on our gmail account.

For email verification, we can directly click the Verify Email Address button, then we will be directed to the home page.

OK, we have succeeded in making email verification in laravel 8 with gmail. That's all for this article, if you have suggestions, criticisms, input or whatever you want to discuss, please write them in the comment form below

Last updated