2017-04-24 52 views
4

我正在使用Laravel 5.4並嘗試實現身份驗證系統。我用php artisan命令make:auth來設置它。根據我的佈局編輯視圖。現在,當我試圖註銷它扔我這個錯誤如何使用Laravel 5.4註銷並重定向到登錄頁面?

NotFoundHttpException在RouteCollection.php線161:

可以在任何一個可以幫助我如何註銷?

+0

將您的代碼發送至? –

回答

14

在你web.php(路線):

地址:

Route::get('logout', '\App\Http\Controllers\Auth\[email protected]'); 

在你LoginController.php

地址:

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

此外,在LoginController.php頂部,後namespace

地址:

use Auth; 
use Illuminate\Http\Request; 

現在,您就可以使用yourdomain.com/logout URL來註銷,或者如果你已經創建logout button,加HREF到/logout

+0

非常感謝Tauras,它的工作:) –

+0

工作就像一個魅力!謝謝,, –

+0

爲什麼不使用laravel預建的'auth routes'? – Sid

11

即使@Tauras提出的建議只是起作用,我不認爲這是處理這個問題的正確方法。

你說你運行了php artisan make:auth,它也應該在你的routes/web.php路由文件中插入Auth::routes();。其中默認的logout路由已經定義並命名爲logout

你可以see it here on GitHub,但我還會在這裏報告的代碼簡單:

/** 
    * Register the typical authentication routes for an application. 
    * 
    * @return void 
    */ 
    public function auth() 
    { 
     // Authentication Routes... 
     $this->get('login', 'Auth\[email protected]')->name('login'); 
     $this->post('login', 'Auth\[email protected]'); 
     $this->post('logout', 'Auth\[email protected]')->name('logout'); 
     // Registration Routes... 
     $this->get('register', 'Auth\[email protected]')->name('register'); 
     $this->post('register', 'Auth\[email protected]'); 
     // Password Reset Routes... 
     $this->get('password/reset', 'Auth\[email protected]')->name('password.request'); 
     $this->post('password/email', 'Auth\[email protected]')->name('password.email'); 
     $this->get('password/reset/{token}', 'Auth\[email protected]')->name('password.reset'); 
     $this->post('password/reset', 'Auth\[email protected]'); 
    } 

然後再請注意logout需要POST作爲HTTP請求方法。這背後有很多有效的原因,但只要提一個非常重要的是,這樣可以防止跨站請求僞造

那麼根據我剛纔指出了一個正確的方式來實現,這可能只是這樣的:

<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('frm-logout').submit();"> 
    Logout 
</a>  
<form id="frm-logout" action="{{ route('logout') }}" method="POST" style="display: none;"> 
    {{ csrf_field() }} 
</form> 

最後請注意,我已經插入laravel開箱準備功能{{ csrf_field() }}的!

0

您可以使用您的控制器如下:

return redirect('login')->with(Auth::logout()); 
0

在5。5

加入

Route::get('logout', 'Auth\[email protected]');

我的路線文件工作正常。

+0

不這樣做,看到Sid的迴應。其他網站可以將用戶註銷,同時將某人重定向到domain.com/logout – kendepelchin

+0

哦,很酷,很高興知道 – Beefjeff

0

如果您使用的身份驗證腳手架5.5乾脆直接您href到:

{{ route('logout') }} 

無需改變任何路線或控制器。

相關問題