I am loging out user through following code. This is my view code behind logout button:
\"&g
u can change the view code and echo instead of
<li>
<a href="<?= Url::to(['site/logout'])?>">
<i class="fa fa-sign-out"></i> Log out
</a>
</li>
this one:
<?= Html::a('<i class="fa fa-sign-out"></i>',
['/site/logout'],
['class'=>'btn btn-default btn-flat']), //optional* -if you need to add style
['data' => ['method' => 'post',]])
?>
this code is working for AdminLTE template.
['label' => 'Sign out (' . Yii::$app->user->identity->username . ')','url' => ['/site/logout'],'template' => '<a href="{url}" data-method="post">{label}</a>',],
Following works too assuming you might extra class and data-method
attribute.
<?=
Html::a(
'Logout (' . Yii::$app->user->identity->username . ')',
['/site/logout'],
['class' => 'ui inverted button', 'data-method' => 'post']
);
?>
You can also use a custom template
'items' => [
[
'label' => 'Logout',
'url' => ['/user/security/logout'],
'template' => '<a href="{url}" data-method="post">{label}</a>',
],
]
Seems like you have VerbFilter
attached to logout
action in your SiteController
:
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
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 add data-method
attribute to request with POST:
<a href="<?= Url::to(['site/logout'])?>" data-method="post">...</a>
Update: Another reason of this problem can be missing dependency for yii\web\YiiAsset. Make sure it's included in AppAsset
:
public $depends = [
'yii\web\YiiAsset',
...
];
YiiAsset
provides data-method
attribute feature which gives possibility to link act as a form with action post
by writing less code. Without asset obviously link will act as regular link and standard GET request will be sent.
If you are using Nav::widget
to generate menus, the logout item should have linkOptions
specified:
[
'label' => '<i class="fa fa-sign-out"></i>Logout',
'url' => ['/logout'],
'linkOptions' => ['data-method' => 'post'],
],