Laravel 8: Система проверки электронной почты
Проверка электронной почты в laravel 4, 5, 6, 7, 8; В этом руководстве вы узнаете, как создать собственную систему проверки электронной почты в приложении laravel.
Пример настраиваемой системы проверки электронной почты laravel
Используйте следующие шаги, чтобы создать собственную систему проверки электронной почты в приложениях laravel 4, 5, 6, 7, 8:
Шаг 1. Создайте таблицу "users_verify" с помощью миграции
Выполните следующую команду в своем терминале, чтобы создать таблицу users_verify в своей базе данных с помощью миграции laravel:
php artisan make:model UserVerify -m
Затем посетите директорию database/migration, откройте файл create_users_verify_table.php и добавьте следующий код в свой файл, как показано ниже:
<?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()
{
}
}
Шаг 2: Обновите модель
Теперь откройте два файла моделей user.php и UserVerify.php. Затем обновите следующий код в этих файлах, как показано ниже:
Обновите следующий код в файле 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
{
use HasFactory, Notifiable;
/**
* Атрибуты, которые можно назначать массово.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'is_email_verified'
];
/**
* Атрибуты, которые должны быть скрыты для массивов.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Атрибуты, которые следует приводить к собственным типам.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Затем обновите следующий код в файле app/Models/UserVerify.php как показано ниже:
<?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);
}
}
Шаг 3. Создайте маршрут (Route)
Посетите каталог /routes/, откройте файл web.php и создайте собственный маршрут для проверки электронной почты, как показано ниже:
<?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');
/* Новые добавленные маршруты */
Route::get('dashboard', [AuthController::class, 'dashboard'])->middleware(['auth', 'is_verify_email']);
Route::get('account/verify/{token}', [AuthController::class, 'verifyAccount'])->name('user.verify');
Шаг 4. Обновите контроллер аутентификации
Посетите каталог app/Http/Controllers/Auth/ и откройте файл вашего контроллера аутентификации (в нашем случае это контроллер AuthController.php) и обновите в нем следующие методы:
<?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);
}
}
Шаг 5: Создайте файл Blade
Посетите каталог resources/views/emails/ и создайте файл emailVerificationEmail.blade.php. Затем обновите в нем следующий код;
<h1>Email Verification Mail</h1>
Please verify your email with bellow link:
<a href="{{ route('user.verify', $token) }}">Verify Email</a>
Шаг 6: Создание Middleware
Выполните следующую команду в своем терминале, чтобы создать файл middleware:
php artisan make:middleware IsVerifyEmail
Затем перейдите в каталог app/Http/Middleware/ и откройте файл IsVerifyEmail.php как показано ниже:
<?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);
}
}
Затем зарегистрируйте middleware в файле kernel.php поэтому зайдите в каталог app/Http/, откройте файл Kernel.php и обновите в нем следующий код:
protected $routeMiddleware = [
....
'is_verify_email' => \App\Http\Middleware\IsVerifyEmail::class,
];
Шаг 7. Конфигурация электронной почты
Обновите данные конфигурации электронной почты, поэтому откройте файл .env и обновите данные конфигурации электронной почты, как показано ниже:
MAIL_DRIVER=smtp
MAIL_HOST=smtp-mail.outlook.com
MAIL_PORT=587
MAIL_USERNAME=example@hotmail.com
MAIL_PASSWORD=123456789
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=example@hotmail.com
Шаг 8: Запустите сервер разработки
Выполните следующую команду в терминале, чтобы запустить сервер разработки:
php artisan serve
Посетители, находящиеся в группе Гости, не могут оставлять комментарии к данной публикации.