人気のPHP WEBアプリケーションフレームワークLaravelのTipsを記録していきます

Laravelでメール認証をログインさせずに行う

● Laravelでメール認証をログインさせずに行う

Laravelではメール認証を行う時、すでにログインをされた状態 である必要があります

ログインしていなくてもメール認証のみ実行するように変えてみましょう

1. 現在のルーティングを確認する

php artisan route:list
Method URI Name Action Middleware
GET|HEAD email/verify/{id}/{hash} verification.verify App\Http\Controllers\Auth\VerificationController@verify web
auth
signed
throttle:6,1

ミドルウェアに auth が入っています。これがあると、ログインしていない場合は、ログイン画面へ飛ばされます。


2. VerificationController.phpを変更する

auth ミドルウェアを外します。

app/Http/Controllers/Auth/VerificationController.php

    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }

  ↓ auth ミドルウェアをコメントアウト

    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }


3. VerificationController.phpに verify メソッドを追加する

app/Http/Controllers/Auth/VerificationController.php

    /**
     * 
     * メールアドレス確認(メソッドのオーバーライド)
     * 
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     *
     */
    public function verify(Request $request)
    {
        $user = \App\User::find($request->route('id'));
    
        if (!hash_equals((string) $request->route('hash'), sha1($user->getEmailForVerification()))) {
            throw new AuthorizationException;
        }
    
        if ($user->markEmailAsVerified())
            event(new \Illuminate\Auth\Events\Verified($user));
    
        return redirect($this->redirectPath())->with('verified', true);
    }

これでokです。

No.1872
10/05 15:10

edit