Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 redirect in init does it work or not?

class TestController extends Controller {
    function init() {
       if(!(strtolower(yii::$app->requestedRoute) == "account/login" || empty(yii::$app->requestedRoute)))
       {
           if (false===$this->isLogin()) {

               return $this->redirect('/login');   //it works, will redirect

           }
       } else {
           if($this->isLogin()) {
               return $this->redirect('/purchaser/manifest');   //not work, won't redirect
                //echo $this->redirect('/purchaser/manifest');    //work


           }
       }
   }
}

I had overriden Controller. When I tried to do filter, I found this problem. I'm confused, any help?

like image 574
kestrel Avatar asked Dec 12 '25 23:12

kestrel


1 Answers

From Yii2 docs:

In case the action should not run, the request should be handled inside of the beforeAction code by either providing the necessary output or redirecting the request. Otherwise the response will be empty.

public function beforeAction($action)
{
    if (!parent::beforeAction($action)) {
         return false;
    }
    // your custom code here
    //Eg
    if(something){
         $this->redirect('/login');
         return false; //not run the action
    }

    return true; // continue to run action
}

Yii2 not care about return value of init() function. Applications will still continue to run action. About redirect() function, It will not work until application completed (beforeAction return false or an action return). So when you call redirect() in init() function nothing happens.
But return $this->redirect('/login'); It works. Why? Because in this case, application redirect after run your action.
you can try, even write $this->redirect('/login'); It still works.

like image 68
Ngô Văn Thao Avatar answered Dec 15 '25 19:12

Ngô Văn Thao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!