Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 redirect in controller action does not work?

Tags:

redirect

yii2

I am posting a form to /user/save in order to save user data. The problem occurs when i try to redirect the user if the $_SERVER['REQUEST_METHOD'] is NOT 'post'.

My user controller code

namespace app\controllers; use Yii; use yii\web\Controller; use app\models\MyUser;  class UserController extends Controller {  public function actionSave() {      if(!Yii::$app->request->getIsPost()) {        $this->redirect('/user/index',302);        exit(0);    }     //do something to save user submitted data        }  }//~CLASS 

The is no way to get the redirection to work. Although !Yii::$app->request->getIsPost() is false the call to $this->redirect does nothing!

Any help appreciated.

like image 328
Andreas Avatar asked May 27 '14 15:05

Andreas


People also ask

How to redirect to controller in Yii2?

Please show us the controller code where you are trying to redirect. Try this: return $this->redirect(array('site/dashboard')); It will definitely work!

How to redirect in Yii?

Yii::app()-request->redirect('/path/to/url');


2 Answers

In Yii2 we need to return() the result from the action.I think you need to add a return in front of your redirect.

  return $this->redirect(['user/index']); 
like image 88
Dency G B Avatar answered Sep 21 '22 18:09

Dency G B


If you are trying to do redirect in beforeAction() you should use send() method

 return $this->redirect('/some/url',302)->send(); 
like image 44
Denhell Avatar answered Sep 20 '22 18:09

Denhell