Code after redirect executes

I have a quick question about the redirect.

I was trying below code:

// Controller
public function actionDelete($id){
    $model = $this->findModel($id);
    $this->checkPermission($model);
    $model->delete();
}

public function checkPermission($model)  {
    if(!Yii::$app->user->can('admin')){
        Yii::$app->session->setFlash('warning', Yii::t('app', 'You do not have permission to perform this action.'));
          return $this->redirect(['controller/view', 'id' => $model->id]);
    }
}

when user without “admin” permission triggers delete action, it redirect as given in checkPermission function and also shows message but then it also deletes the object. Which means right after checkPermission redirect, it still continues executing $model->delete(); is this expected behaviour ??

$this->redirect() does not stop execution flow, just configures response object and returns it. Since you ignore $this->checkPermission($model) result in actionDelete(), the rest of the code in actionDelete() is also executed. You need something like this:

if ($this->checkPermission($model) === null) {
    $model->delete();
}

Or refactor checkPermission() to throw exception, which AFAIK is preferred way of breaking execution flow in case of missing permissions.

1 Like

Thank you for clarification… :pray: I did try throwing exception and it works and yes conditioning the check as well.