algolia search

Tìm thấy x bài viết trong xms.

Laravel 5.7 Email Verification

Laravel 5.7 Email Verification


1. Giới thiệu

Nhiều ứng dụng web yêu cầu người dùng xác minh địa chỉ email của họ trước khi sử dụng ứng dụng. Thay vì buộc bạn phải thực hiện lại điều này trên mỗi ứng dụng, Laravel đã cung cấp các phương thức để gửi và xác minh các yêu cầu xác minh email một cách thuận tiện hơn.

2. Tích hợp Email Verification cho các phiên bản Laravel 5.7 trở về trước

Đối với các ứng dụng Laravel 5.7 mới chắc chắn đã tích hợp sẵn tính năng này, nên bài viết này dùng để áp dụng cho các phiên bản trước tích hợp tính năng vào ứng dụng hiện tại.

2.1. Implements MustVerifyEmail vào User model

File laravel\app\User.php cần implements MustVerifyEmail class

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use 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',
    ];
}

2.2. Thêm cột email_verified_at vào bảng users

Chạy lệnh artisan sau:

php artisan make:migration add_email_verified_at_to_users --table=users

Sẽ sinh ra file database\migrations\2018_08_23_102246_add_email_verified_at_to_users.php ta sửa lại như sau:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddEmailVerifiedAtToUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->timestamp('email_verified_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('email_verified_at');
        });
    }
}

Chạy lệnh php artisan migrate để thêm cột vào bảng

2.3. Chỉnh lại route

Nếu bạn sử dụng authentication mặc định của Laravel (php artisan make:auth) thì trong file routes\web.php của bạn chắc chắn có dòng sau:

Auth::routes();

Bạn chỉnh lại như dưới đây để bật tính năng email verification nhé:

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

2.4. Bảo vệ routes bằng verified middleware

Nếu bạn muốn trong ứng dụng của bạn, người dùng truy cập vào trang profile thì bắt buộc phải xác nhận email rồi mới được vào bạn làm như sau:

Trong file app\Http\Kernel.php thêm middleware verified:

protected $routeMiddleware = [
    ...
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

Vậy là ngoài routes bạn có thể bảo vệ routes verified middleware

Route::get('profile', function () {
    // Chỉ những người dùng xác nhận email rồi mới được vào
})->middleware('verified');

2.5. Views

Bạn hãy chạy lệnh artisan php artisan make:auth một lần nữa nếu chạy rồi. Bạn sẽ thấy file resources\views\auth\verify.blade.php nhé, bạn thoải mái chỉnh sửa file này theo ý muốn của bạn.

2.6. VerificationController

Phần quan trọng nhất là controller xử lý email verify. Nếu trong ứng dụng bạn chưa có file app\Http\Controllers\Auth\VerificationController.php thì bạn có thể tạo bằng tay hoặc chạy lệnh artisan sau nhé: php artisan make:controller Auth/VerificationController

File app\Http\Controllers\Auth\VerificationController.php có nội dung như sau:

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be resent if the user did not receive the original email message.
    |
    */

    use VerifiesEmails;

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }
}

Bạn có thể thấy protected $redirectTo = '/home'; chính là đường dẫn chuyển hướng người dùng sau khi xác nhận email. Như vậy bạn có thể thay thành đường dẫn bạn muốn chẳng hạn: protected $redirectTo = '/dashboard'; hay protected $redirectTo = '/';

3. Video

Like fanpage Group Facebook Laravel Việt Nam Laravel để cập nhật thường xuyên các bạn nhé!

Đánh giá bài viết

Thích thì like
Laravel 5.7 Email Verification
5/5 1 votes

Bình luận

quyen van avatar
quyen van
em đã đổi tên bảng user mặc định thì có làm được theo hướng dẫn ko a. e phải đổi tên những thành phần tên ở đâu để phù hợp với tên mà em đã đổi ạ

Chung Nguyễn avatar
Chung Nguyễn
Đổi tên bảng không ảnh hưởng gì lắm, em chỉ cần cấu hình trong eloquent model là được. Em thử làm theo hướng dẫn ok k nhé.
Lê Xuân Trường avatar
Lê Xuân Trường

Nay em mới mò tới thằng 5.7 mà giờ các bước add colume, middleware nó sai báo sẵn rồi anh ạ. 

Chung Nguyễn avatar
Chung Nguyễn

Bài viết anh hướng dẫn update từ 5.6 lên 5.7 á em, nếu em cài mới Laravel 5.7 đương nhiên là nó khai báo sẵn rồi :D

Hiển thị bình luận Facebook