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


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

我正在Laravel 5.2中构建一个非常简单的应用程序,但当使用AuthController的操作注销时,它根本不起作用。我有一个导航栏,它检查Auth::check(),在调用注销操作后不会更改。

我在routes.php文件中有这个路由:

Route::get('users/logout', 'Auth'AuthController@getLogout');

它在外面

Route::group(['middleware' => ['web']], function ()语句。

我还尝试在AuthController.php文件的末尾添加以下操作。

public function getLogout() 
{
    $this->auth->logout();
    Session::flush();
    return redirect('/');
}

你有什么想法吗?

编辑1

如果我清除谷歌的Chrome缓存,它就会工作。

我在Laravel 5.2中也遇到了类似的问题。你应该把你的路线改成

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

或在AuthController构造函数中添加

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

这对我很有效。

使用以下代码

Auth::logout();

auth()->logout();

问题来自AuthController构造函数中的"guest"中间件。应将其从$this->middleware('guest', ['except' => 'logout']);更改为$this->middleware('guest', ['except' => 'getLogout']);

如果您检查内核文件,您可以看到您的客户中间件指向'App'Http'Middleware'RedirectIfAuthenticated::class

该中间件检查用户是否已通过身份验证,并在通过身份验证时将用户重定向到根页面,但在未通过身份验证的情况下允许用户执行操作。通过使用$this->middleware('guest', ['except' => 'getLogout']);,在调用getLogout函数时不会应用中间件,从而使经过身份验证的用户可以使用它。

N/B:与原来的答案一样,您可以将getLogout更改为logout,因为getLogout方法只是返回laravel实现中的logout方法。

Http->Middleware->Authenticate.php中将else语句中的login更改为/

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

并在routes.php 中定义以下路由

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

用于注销调用以下功能:

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

重要信息:重定向到/home,而不是/,后者首先调用$this->middleware('auth');,然后在中间件中重定向到/

这应该是AuthController 中构造函数的内容

$this->middleware('web');
$this->middleware('guest', ['except' => 'logout']);

只需在路由下面添加,不要在任何路由组(中间件)中添加:

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

现在注销应该可以像在L5.2中一样工作,而不需要修改AuthController中的任何内容。

/**
 * Log the user out of the application.
 *
 * @param 'Illuminate'Http'Request  $request
 * @return 'Illuminate'Http'Response
 */
public function logout(Request $request)
{
    $this->guard()->logout();
    $request->session()->flush();
    $request->session()->regenerate();
    return redirect('/');
}
/**
 * Get the guard to be used during authentication.
 *
 * @return 'Illuminate'Contracts'Auth'StatefulGuard
 */
protected function guard()
{
    return Auth::guard();
}

routes.php文件Route::get('auth/logout', 'Auth'AuthController@getLogout');中添加此行并将其添加到您的视图中<a href="{{ url('/auth/logout') }}" > Logout </a>它对我来说很好