I am loging out user through following code. This is my view code behind logout button:
<li>
<a href="<?= Url::to(['site/logout'])?>">
<i class="fa fa-sign-out"></i> Log out
</a>
</li>
My controller code is:
public function actionLogout()
{
Yii::$app->user->logout();
$model = new LoginForm();
$this->layout = 'index';
return $this->render('login', ['model' => $model]);
}
In the logout it shows me:
Method Not Allowed. This url can only handle the following request methods: POST.
What is it?
Seems like you have
VerbFilter
attached tologout
action in yourSiteController
:That means this action can requested only with POST method, and you are requesting with GET, that's why exception #405 is thrown.
Either remove this from
VerbFilter
or adddata-method
attribute to request with POST:Update: Another reason of this problem can be missing dependency for yii\web\YiiAsset. Make sure it's included in
AppAsset
:YiiAsset
providesdata-method
attribute feature which gives possibility to link act as a form with actionpost
by writing less code. Without asset obviously link will act as regular link and standard GET request will be sent.u can change the view code and echo instead of
this one:
Following works too assuming you might extra class and
data-method
attribute.You must only replace 'logout' => ['post'], with 'logout' => ['get']. In this way your error will be solved.
This way works only with Yii Framework version 2.
You can also use a custom template
If you are using
Nav::widget
to generate menus, the logout item should havelinkOptions
specified: