james james - 10 months ago 81
reST (reStructuredText) Question

Restrict certain attributes from updating Yii2

I am making a REST API using Yii2. In Put request method during update i want to restrict user to not able to update his/her email address. Is there a way that we can achieve this? Right now when user send put request with changed email address the email address gets changed.

Answer Source

Use model scenarios See Model Scenarios


namespace app\models;

use yii\db\ActiveRecord;

class User extends ActiveRecord
    const SCENARIO_API = 'API';

    public function scenarios()
        return [
            self::SCENARIO_API => ['username', 'password'],
            self::SCENARIO_OTHER => ['username', 'email', 'password'],


namespace app\controllers;
use yii\rest\ActiveController;
use app\models\User;

class UserController extends ActiveController
    public $modelClass = 'app\models\User';
    public $createScenario = User::SCENARIO_API;