How to logout with a GET request in Laravel

Viewed 14605

I am getting error when i am logout, it's showing me this error..."The GET method is not supported for this route. Supported methods: POST." Please help me to solve this issue..

Here are my code...

@if(Auth::check())
  <li><i class="fa fa-user"></i> {{Auth::user()->name}}:
    <a href="{{url('logout')}}">logout</a>
  </li>
@else
  <li>
    <a href="{{route('login')}}"><i class="fa fa-user"></i>Login</a>
  </li>
@endif
5 Answers

You could just add this line in your web.php routes file:

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

This allows you to logout by using a GET Request.

Use

<a href="{{ route('logout') }}">Logout</a>

and in route file

Route::get('logout', function ()
{
    auth()->logout();
    Session()->flush();

    return Redirect::to('/');
})->name('logout');

GET method in not supported for logout. Laravel 5.4+ uses post method for logout so instead of simple GET request you should POST a form to logout.

Ex. :

<form id="logout-form" action="{{ url('logout') }}" method="POST">
            {{ csrf_field() }}
    <button type="submit">Logout</button>
</form>

Change in your code :

@if(Auth::check())
<li><i class="fa fa-user"></i> {{Auth::user()->name}}:</li>
        <form id="logout-form" action="{{ url('logout') }}" method="POST">
                    {{ csrf_field() }}
            <button type="submit">Logout</button>
        </form>
      @else
    <li><a href="{{route('login')}}"><i class="fa fa-user"></i>
            Login
        </a>
    </li>
@endif
@if(Auth::check())
  <li><i class="fa fa-user"></i> {{Auth::user()->name}}:
    <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>
  </li>
@else
  <li>
    <a href="{{route('login')}}"><i class="fa fa-user"></i>Login</a>
  </li>
@endif

You're using the href attribute of a link to call the according URL - these links however always use GET HTTP calls to open/call the according target. As the error message states, the target you're calling is expecting a POST HTTP call.

Knowing what your problem is, you'd probably find this StackOverflow answer which should help you resolve the problem in a way that suits you: Making href anchor tag request post instead of get

Related