尤川豪   ·  5年前
445 貼文  ·  275 留言

「註冊後收 Email 確認啟動帳號」功能的實作方式比較(Laravel)

Laravel 5.7 開始有官方內建這項功能可以用

我手上案子是 5.3 的需要自己實作 比較一下其他人的作法

https://lubus.in/blog/adding-email-verification-in-laravel-5-3-app-149?utm_source=learninglaravel.net

http://bensmith.io/email-verification-with-laravel

migration

$table->tinyInteger('verified')->default(0); // this column will be a TINYINT with a default value of 0 , [0 for false & 1 for true i.e. verified]
$table->string('email_token')->nullable(); // this column will be a VARCHAR with no default value and will also BE NULLABLE
$table->boolean('confirmed')->default(0);
$table->string('confirmation_code')->nullable();

都一樣 需要存驗證碼的欄位 需要存驗證與否的欄位

驗證碼

'email_token' => str_random(10),
$confirmation_code = str_random(30);

都是用 str_random 產生驗證碼

寄信手法

    DB::beginTransaction();
    try
    {
        $user = $this->create($request->all());
        // After creating the user send an email with the random token generated in the create method above
        $email = new EmailVerification(new User(['email_token' => $user->email_token, 'name' => $user->name]));
        Mail::to($user->email)->send($email);
        DB::commit();
        return back();
    }
    catch(Exception $e)
    {
        DB::rollback(); 
        return back();
    }
        User::create([
            'username' => Input::get('username'),
            'email' => Input::get('email'),
            'password' => Hash::make(Input::get('password')),
            'confirmation_code' => $confirmation_code
        ]);

        Mail::send('email.verify', $confirmation_code, function($message) {
            $message->to(Input::get('email'), Input::get('username'))
                ->subject('Verify your email address');
        });

都是在 controller 裡面 直接在註冊同時寄送

用 Laravel Events & Listeners 好像比較酷 可是沒關係 反正這樣比較簡單

阻擋未驗證帳號

use Illuminate\Http\Request;

// ...

public function credentials(Request $request)
{
    return [
        'email' => $request->email,
        'password' => $request->password,
        'verified' => 1,
    ];
}
        $credentials = [
            'username' => Input::get('username'),
            'password' => Input::get('password'),
            'confirmed' => 1
        ];

就是在 credential 加上驗證與否欄位

  分享   共 3,059 次點閱
共有 0 則留言
還沒有人留言。歡迎分享您的觀點、或是疑問。
您的留言
尤川豪
445 貼文  ·  275 留言

Devs.tw 是讓工程師寫筆記、網誌的平台。隨手紀錄、寫作,方便日後搜尋!

歡迎您一起加入寫作與分享的行列!

查看所有文章