Logging out via a link in Laravel

Ben Kao picture Ben Kao · Mar 29, 2017 · Viewed 46.7k times · Source

I have a "Logout" link in my top navigation bar. I'm wondering how I can make it so that while I'm logged in, it'll log me out when I click on it and return me to the homepage.

To be specific, what changes to which files do I make in Laravel? Also, what code do I need to write in the view, which currently contains just HTML, to trigger this?

Answer

Lucas Bustamante picture Lucas Bustamante · Mar 30, 2018

When you run php artisan make:auth, the default app.php in Laravel 5.5 does it like this:

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

<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
    {{ csrf_field() }}
</form>