Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way to redirect on login page in yii2

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 ?

like image 977
Nikul Avatar asked Nov 30 '22 10:11

Nikul


1 Answers

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' => ['@'],
        ],
    ],
],
like image 81
GAMITG Avatar answered Dec 24 '22 09:12

GAMITG