Laravel 5.2: Auth::logout() is not working

前端 未结 8 1435
孤独总比滥情好
孤独总比滥情好 2020-12-16 00:04

I\'m building a very simple app in Laravel 5.2, but when using AuthController\'s action to log out, it just simply doesn\'t work. I have a nav bar which checks

相关标签:
8条回答
  • 2020-12-16 00:14

    add this line in routes.php file Route::get('auth/logout', 'Auth\AuthController@getLogout'); and add this in your view <a href="{{ url('/auth/logout') }}" > Logout </a> it works fine for me

    0 讨论(0)
  • 2020-12-16 00:20

    I also had similar problem in Laravel 5.2. You should change your route to

    Route::get('auth/logout', 'Auth\AuthController@logout');
    

    or in AuthController constructor add

    public function __construct()
    {
        $this->middleware('guest', ['except' => ['logout', 'getLogout']]);
    }
    

    That worked for me.

    0 讨论(0)
  • 2020-12-16 00:22

    The problem is from the 'guest' middleware in the AuthController constructor. It should be changed from $this->middleware('guest', ['except' => 'logout']); to $this->middleware('guest', ['except' => 'getLogout']);

    If you check the kernel file, you can see that your guest middleware point to \App\Http\Middleware\RedirectIfAuthenticated::class

    This middleware checks if the user is authenticated and redirects the user to the root page if authenticated but lets the user carry out an action if not authenticated. By using $this->middleware('guest', ['except' => 'getLogout']); , the middleware will not be applied when the getLogout function is called, thereby making it possible for authenticated users to make use of it.

    N/B: As in the original answer, you can change getLogout to logout since the getLogout method simply returns the logout method in laravel's implementation.

    0 讨论(0)
  • 2020-12-16 00:24

    In Http->Middleware->Authenticate.php change login in else statement to /

    return redirect()->guest('/');
    

    and define following route in routes.php

    Route::get('/', function () {
        return view('login');
    });
    

    for logout call following function:

    public function getlogout(){
        \Auth::logout();
        return redirect('/home');
    }
    

    Important: redirect to /home instead of / that first calls $this->middleware('auth'); and then in middleware redirect to /

    0 讨论(0)
  • 2020-12-16 00:25

    Simply add below route and do not add this inside any route group(middleware):

    Route::get('your-route', 'Auth\AuthController@logout');
    

    Now logout should work as it should in L 5.2 without modifying anything in AuthController.

    0 讨论(0)
  • 2020-12-16 00:28

    This should be the content of your constructor in AuthController

    $this->middleware('web');
    $this->middleware('guest', ['except' => 'logout']);
    
    0 讨论(0)
提交回复
热议问题