Search code examples
phpactiverecordyii2yii2-advanced-app

Yii2 model public attributes


I have a User model with some attributes that are public and some that are db column attributes

Assume that the model have N many public attributes (Email and Surname for example) and column attributes (Salt, confirmation_token for example)

I want to loop through all attributes in a model including public attributes and db column attributes


Solution

  • Assuming your User model is an ActiveRecord you can create a function like this to retrieve the combination of the public attributes and the ones retrieved from the database.

    public function getAllAttributes() {
        return array_merge(
            parent::attributes(),
            \yii\base\Model::attributes()
        );
    }
    

    Printing the values of the attributes can then be done like

    $attributes = $model->getAllAttributes();
    foreach ($attributes as $attribute) {
        echo $model->$attribute;
        echo "<br />";
    }