LoginSignup
14
12

More than 5 years have passed since last update.

「PHP」「laravel」認証のメールを作りましょう

Posted at

ユーザーが登録してから、認証メールをもらいます。その認証メールの中でリンクがあり、リンクを押したら、ユーザーがベリバイドになります。そするとローギンできます。つまりベリバイドしてない限り、ローギンできないということです。ここでやり方をちょっと説明します。

1。まずはユーザーテーブルで「verified」と「email_token」のカラムを作りましょう。

    $table->tinyInteger('verified')->default(0);
    $table->string('email_token')->nullable();

最初「verified」のカラムに0をあげて、ユーザーがベリバイドしてから1になります。「email_token」のカラムに秘密キーを保存します。そしてUser.phpを修正しましょう。「fillable」の変数に「verified」と「email_token」を追加しましょう。『もしいちいち追加するのが面倒だと思うなら、fillableの変数を消して、$guarded=[] に変更してもいいです。それを使うなら利点があるけれど、不利点もあるので気をつけないといけません』。そして「php artisan migrate」とか「php artisan migrate:refresh」を実行するのを忘れないでください。

2。そして「php artisan make:auth」を実行しましょう。もっと詳しく知りたければ、「https://laravel.com/docs/5.5/authentication」
で読めます。次はAuth/LoginControllerのクラスに修正しましょう。
もしユーザーがベリバイドしてない限り、ローギンできないということにしましょう。

protected function credentials(Request $request) {
    return array_merge($request->only($this->username(), 'password'), ['verified' => 1]);
 }

3。今「.env」のファイルを修正しましょう。メールのところに修正しましょう。ここでgmailやmailtrapなどを使えます。例:
これはgmailを使うなら、こいうふうになります。

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_FROM_ADDRESS=myemail@gmail.com(ここで好きな名前を使ってください)
MAIL_FROM_NAME=ハルだよ(ここで好きな名前を使ってください)
MAIL_USERNAME=メールのユーザーネーム
MAIL_PASSWORD=メールのパスワード
MAIL_PRETEND=false
MAIL_ENCRYPTION=tls

でも開発の時、mailtrapを使った方がいいと思います。mailtrapは使いやすいし、便利だし、無料ですから。https://mailtrap.ioで新しアカウントを登録できます。そして「demo inbox」を押したら、smtp設定が出てきます。

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=メールのユーザーネーム
MAIL_PASSWORD=メールのパスワード
MAIL_FROM_ADDRESS=myweb@example.com(ここで好きな名前を使ってください)
MAIL_FROM_NAME=ハルだよ(ここで好きな名前を使ってください)
MAIL_PRETEND=false
MAIL_ENCRYPTION=tls

毎回「.env」を修正する時、「php artisan config:clear」を実行するのを忘れなしでください。

4。次はLaravelのメールのサービスをたてましょう。「php artisan make:mail EmailVerification --markdown=emails.verification」を実行しましょう。そすると「Mail」のフォルダーの中で「EmailVerification」のクラスを作成されます。resources/assets/views/emailの中で「email」のクラスも作成されます
。これからこの二つのクラスを修正しましょう。最初「EmailVerification」のクラスでこの変数を追加しましょう。

    Protected $user;

そして「construct」のクラスの中で これを追加しましょう。

    $this->user = $user;

「build」のクラス で修正しましょう。

    return $this->markdown('emails.verification')->with([
                    ‘email_token’ => $this->user->email_token,
        ]);

これで秘密キーが認証メールにつけっています。
次は「verification.blade.php」を修正しましょう。好きなでサインによって修正しましょう。でもこのurlを忘れないでください。そのurlは秘密キーを持っていますから。うちの場合 php artisan serveを使うので、「127.0.0.1:8000」に修正しました。

@component('mail::button', ['url' => 'http://127.0.0.1:8000/verifyemail/$email_token'])
    Verify
@endcomponent

5。これからメールを送るクラスを作成しましょう。そのクラスをphp artisan jobで作成しましょう
。ここで「php artisan make:job SendVerificationEmail」を実行しましょう。そすると「Job」のフォルダーが出てきて、その中で「SendVerificationEmail」があります。そのクラスを修正しましょう。

use Mail;
use App\Mail\EmailVerification;
public function __construct($user)
{
        $this->user = $user;
}
public function handle()
{
        $email = new EmailVerification($this->user);
        Mail::to($this->user->email)->send($email);
}

これでメールをユーザーに送られます。

6。今度はAuth/RegisterControllerのクラスを修正しましょう。上でこれを追加しましょう。

use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use App\Jobs\SendVerificationEmail;

そしてCreateのクラスのreturnのところにこれを追加しましょう。

'email_token' => str_random(10)

安全のために、str_randomを使うと思います。そして本来のRegisterのパスは登録してから、認証メールを使わずにローギンできるので、そのパスを修正しましょう。これを追加しましょう。

  public function register(Request $request)
  {
    $this->validator($request->all())->validate();
    event(new Registered($user = $this->create($request->all())));
    dispatch(new SendVerificationEmail($user));
    return view('/verification');
  }

  public function verify($token)
    {
      $user = User::where('email_token',$token)->first();
      $user->verified = 1;
      if($user->save()){
      return view('/emailconfirm',['user'=>$user]);
      }
    }

ここでパスを変更するために「dispatch(new SendVerificationEmail($user)); return view('/verification’);」を使います。登録してから、ユーザーは「verification.blade.php」に飛ばされます。そして、もし認証メールの中でリンクを押したら、「verify」クラスが実行されて、「verified」のカラムが1に設定して、ユーザーは「emailconfirm.blade.php」に飛ばされます。次は「verification.blade.php」を作成しましょう。例:

verification.blade.php
@extends(layouts.app)

@section(content)
<div class=container>
<div class=row>
<div class=col-md-8 col-md-offset-2">
<div class=”panel panel-default”>
<div class=”panel-heading”>Registration</div>
<div class=”panel-body”>
You have successfully registered. An email is sent to you for verification.
</div>
</div>
</div>
</div>
</div>
@endsection

今度は「emailconfirm.blade.php」を作成しましょう。

emailconfirm.blade.php
@extends(layouts.app)
@section(content)
<div class=container>
<div class=row>
<div class=col-md-8 col-md-offset-2">
<div class=”panel panel-default”>
<div class=”panel-heading”>Registration Confirmed</div>
<div class=”panel-body”>
Your Email is successfully verified. Click here to <a href=”{{url(‘/login’)}}”>login</a>
</div>
</div>
</div>
</div>
</div>
@endsection

7。最後はRoute/web.phpにこれを追加しましょう。
Route::get(‘/verifyemail/{token}’,‘Auth\RegisterController@verify’);

何卒よろしくお願いいたします。

14
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12