I have a controller action that i would like to check if user is a guest in yii2 but the code fails even if the user is a guest this is what i have tried
class CustomerController extends Controller
{
public function beforeAction($action)
{
if(Yii::$app->user->isGuest){
return $this->redirect(Yii::$app->urlManager->createUrl("site/login"));
}
public function actionDashboard(){
//do dashboard stuff
}
}
I have also tried using accessControl filters but they still fail This is the access control filter instance in a Frontend Controller
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'controllers' => ['customer'],
'actions' => ['dashboard'],
'allow' => true,
'users' => ['?'],
],
], // rules
], // access
]; // return
} // behaviors
Then on my customer controller i just extend Frontend Controlller but even with this approach it fails
BY DOING IT THIS WAY
public function actionDashboard(){
if(Yii::$app->user->isGuest){
return $this->redirect(Yii::$app->urlManager->createUrl("site/login"));
}else{
//perform dashboard stuff
}
}
This works but the problem is that by following the last approach there is alot of code duplication in the other actions which doesnt seem right even though it works
What is wrong with the latter approaches which seem better
I have checked on This link and also This second one and implementend them but none works
WHAT COULD BE WRONG.
AM using Yii2 improved advanced template