Laravel 5.4を使って、ログアウトしてログインページにリダイレクトするには?

私はLaravel 5.4を使用しており、認証システムを実装しようとしています。php artisanコマンドのmake:authを使って設定しました。レイアウトに合わせてビューを編集しました。現在、ログアウトしようとすると次のようなエラーが発生します。

RouteCollection.phpの161行目でNotFoundHttpExceptionが発生しました。

誰かログアウトする方法を教えてください。

ソリューション

あなたの web.php (routes)で。

add:

Route::get('logout', '\App\Http\Controllers\Auth\LoginController@logout');

In your LoginController.php.

add:

public function logout(Request $request) {
  Auth::logout();
  return redirect('/login');
}

また、 LoginController.php のトップで、 namespace の後に

add:

use Auth;

これで、 yourdomain.com/logout のURLを使ってログアウトできるようになります。また、 logout button を作成している場合は、 /logout に href を追加します。

解説 (6)

たとえ@Tauras氏の提案がうまくいったとしても、それが正しい対処法とは思えません。

あなたは、php artisan make:authを実行したとおっしゃいましたが、それによってroutes/web.phpルーティングファイルにAuth::routes();が挿入されているはずです。これは、デフォルトの logout ルートがすでに定義されており、logout という名前になっています。

GitHubのここで見ることができますが1、簡単にするためにここでコードを報告します。

    /**
     * Register the typical authentication routes for an application.
     *
     * @return void
     */
    public function auth()
    {
        // Authentication Routes...
        $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
        $this->post('login', 'Auth\LoginController@login');
        $this->post('logout', 'Auth\LoginController@logout')->name('logout');
        // Registration Routes...
        $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
        $this->post('register', 'Auth\RegisterController@register');
        // Password Reset Routes...
        $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
        $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
        $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
        $this->post('password/reset', 'Auth\ResetPasswordController@reset');
    }

また、「logout」はHTTPリクエストメソッドとして「POST」を 必須 としていることにも注意してください。これには様々な理由がありますが、特に重要なのは、この方法で cross-site request forgery を防ぐことができるということです。

私が指摘したことによると、これを実装する正しい方法は次のようになります。

<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('frm-logout').submit();">
    Logout
</a>    

    {{ csrf_field() }}

最後に、Laravel のレディ関数 {{ csrf_field() }} を挿入していることに注意してください!

解説 (1)

コントローラーの中で使用することができます。

return redirect('login')->with(Auth::logout());
解説 (1)