What is best way to redirect on login page in yii2

Nikul picture Nikul · Oct 23, 2015 · Viewed 8.2k times · Source

If user is not logged in then user should have to be redirect on login page, for that i found function which is working fine for me, i used below function

public function beforeAction($action)
{        
    if (\Yii::$app->getUser()->isGuest &&
        \Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
    ) {
        \Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl);
    }
    return parent::beforeAction($action);
}

This is working fine for me, but for this i need to add function in every controller, what i want to do, i need common function where can i perform this action, So can anyone please tell me what is best way to do this ?

Answer

GAMITG picture GAMITG · Oct 23, 2015

You need to add below code in config/web.php after components part.

'as beforeRequest' => [  //if guest user access site so, redirect to login page.
    'class' => 'yii\filters\AccessControl',
    'rules' => [
        [
            'actions' => ['login', 'error'],
            'allow' => true,
        ],
        [
            'allow' => true,
            'roles' => ['@'],
        ],
    ],
],