LoginSignup
4
5

More than 5 years have passed since last update.

Laravel 5.2 では認証周りのアクション名が変わってます

Posted at

はじめに

Laravel 5.1 のドキュメントを見ながら Laravel 5.2 で開発をしていたら、ログアウトができなくてハマったので、何が原因でハマったかをメモしておきます。

現象

ルータには以下のようにログアウトのためのルートを登録していて

app/Http/routes.php
Route::get('auth/logout', 'Auth\AuthController@getLogout');

ブラウザから /auth/logout にはアクセスできていたのですが、アクセスしてもログアウト処理はされず、app/Http/Controller/Auth/AuthController.phpgetLogout() メソッドも呼ばれていませんでした。

原因

概要

Laravel 5.2 からログアウトに使うアクションが変わったのに、ルータに古いアクションを指定していたのが原因でした。

Laravel 5.2 でログアウトに使うアクションが変更された

Laravel 5.1 の公式ドキュメントを見ると、ログイン周りのルートを登録するには、以下のように書くよう指示されています。

app/Http/routes.php
// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

これが Laravel 5.2 のドキュメントでは以下のように Artisan コマンドを使って登録するように指示されていて

$ php artisan make:auth

この通り実行すると、ルートには

app/Http/routes.php
Route::auth();

が登録されます。

Route::auth() の中を見てみると

vendor/laravel/framework/src/Illuminate/Routing/Router.php
/**
 * Register the typical authentication routes for an application.
 *
 * @return void
 */
public function auth()
{
    // Authentication Routes...
    $this->get('login', 'Auth\AuthController@showLoginForm');
    $this->post('login', 'Auth\AuthController@login');
    $this->get('logout', 'Auth\AuthController@logout');

    // Registration Routes...
    $this->get('register', 'Auth\AuthController@showRegistrationForm');
    $this->post('register', 'Auth\AuthController@register');

    // Password Reset Routes...
    $this->get('password/reset/{token?}', 'Auth\PasswordController@showResetForm');
    $this->post('password/email', 'Auth\PasswordController@sendResetLinkEmail');
    $this->post('password/reset', 'Auth\PasswordController@reset');
}

このようになっていて、ログイン周りのアクション名が変わっていることがわかります。

アクション名を指定してミドルウェアを適用していた

一方で、AuthController の中を見てみると

app/Http/Controllers/Auth/AuthController.php
/**
 * Create a new authentication controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}

このように書かれており、logout 以外のアクションに対してミドルウェア guest を適用しています。
つまり、アクション getLogout には、ミドルウェア guest が適用されてしまっていたのです。

対応

ミドルウェアの設定で logout ではなく getLogout を except するという方法でも解決できますが、Laravel 5.2 のやり方にならって、ルートに登録するアクションを getLogout から logout に変更するのがよいと思います。

おわりに

わかってしまえば単純なことなのですが、私の場合、コントローラからミドルウェアを指定する方法に慣れていなかったため、そういうものだと思って見逃してしまっていました。

4
5
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
4
5