Search code examples
laravellaravel-5laravel-5.3

Why does not work logout route in Laravel?


When I try to logout from admin panel I get error:

MethodNotAllowedHttpException in RouteCollection.php line 218:

But in routing there is route logout:

POST | logout |  App\Http\Controllers\Auth\LoginController@logout | web  

How can I fix this?


Solution

  • You need to do the following steps:

    1.- if you're working with a class created by you to the login, specify it in config/auth.php:

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Administrator::class,
        ],
    ],
    

    2.- your model must inherit from class Authenticatable:

    use Illuminate\Foundation\Auth\User as Authenticatable;
    class Administrator extends Authenticatable{
        #code...
    }
    

    3.- add the logout() function on your LoginController, import Auth and Redirect classes

    public function logout(){
        Auth::logout();
        return Redirect::to('admin');
    }
    

    3.- specify the route that you will use to logout via GET

    Route::get('logout','LoginController@logout');
    

    It is all, this should work.

    NOTE: Check if you are authenticated by the function Auth::check()

    Additional information: When you are working with POST requests, Laravel needs to verify that the request are not a malicious request, for this Laravel needs an ecrypted code, this is called csrf_token, if you don't send this, by default all your requests will be not allowed.