はじめに
Laravel 5.1 のドキュメントを見ながら Laravel 5.2 で開発をしていたら、ログアウトができなくてハマったので、何が原因でハマったかをメモしておきます。
現象
ルータには以下のようにログアウトのためのルートを登録していて
Route::get('auth/logout', 'Auth\AuthController@getLogout');
ブラウザから /auth/logout
にはアクセスできていたのですが、アクセスしてもログアウト処理はされず、app/Http/Controller/Auth/AuthController.php
の getLogout()
メソッドも呼ばれていませんでした。
原因
概要
Laravel 5.2 からログアウトに使うアクションが変わったのに、ルータに古いアクションを指定していたのが原因でした。
Laravel 5.2 でログアウトに使うアクションが変更された
Laravel 5.1 の公式ドキュメントを見ると、ログイン周りのルートを登録するには、以下のように書くよう指示されています。
// 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
この通り実行すると、ルートには
Route::auth();
が登録されます。
Route::auth()
の中を見てみると
/**
* 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
の中を見てみると
/**
* 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
に変更するのがよいと思います。
おわりに
わかってしまえば単純なことなのですが、私の場合、コントローラからミドルウェアを指定する方法に慣れていなかったため、そういうものだと思って見逃してしまっていました。