Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Yii2 $model->save() returns false or saves nothing, with no error shown

Error$model->save() returns false and no row is written

Short answer

Yii2 does not throw when save() fails. It runs validation first and returns false when a rule fails, and the reason sits in $model->errors. If nothing seems wrong there, check that your attributes were really assigned, because only safe attributes in the active scenario are. Print save() and errors together first.

  • Applies to Yii 2.0, PHP 8.3
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Stop calling save() blindly. Print its result together with the errors and the attributes the model really holds. The errors name the failing attribute, and an empty attribute list shows that the assignment never happened.

    $ok = $model->save();
    var_dump($ok, $model->errors, $model->attributes);
    die();
  2. 2Match what you see, then jump to its fix

    1. 1save() returns false and $model->errors is not empty, for example a required or unique ruleA validation rule fails, so save() stops before the queryFix
    2. 2The attributes dump in the first step shows null for a field that the form sentThe attribute is not safe, so the posted value never reached the modelFix
    3. 3The same form works on the create page and fails on the update page, or the other way roundThe model is in a scenario where the attribute is not activeFix
    4. 4save() returns true, and the table row still has the old valuessave() succeeds, but there is nothing to writeFix

What does the error look like?

  • $model->save() returns false and no row is written
  • save() returns true, but the database row did not change
  • A required attribute reports it cannot be blank although the form sent a value

Cause 1 of 4

A validation rule fails, so save() stops before the query

1Check

By default save() calls validate() first, and returns false if validation fails. The errors are kept on the model, and you read them from the errors property.

if (!$model->validate()) {
    var_dump($model->errors);
}

2Fix

Fix the data or the rule that the error names. Only if the data is already known to be right, and for a good reason, call save(false) to skip validation.

// rules() in the model
public function rules()
{
    return [
        [['name', 'email'], 'required'],
        ['email', 'email'],
    ];
}

// controller: show the reason to the user
if (!$model->save()) {
    Yii::$app->session->setFlash('error', json_encode($model->errors));
}

3Verify

Run the request again. save() returns true and the row appears.

var_dump($model->save(), $model->errors);

Confirmed by yiiframework.com

Did this fix it?

Cause 2 of 4

The attribute is not safe, so the posted value never reached the model

1Check

Massive assignment only fills safe attributes. An attribute is safe when it appears in one of the active validation rules. A column that has no rule at all is skipped silently, and a required rule on another column can then fail.

var_dump(Yii::$app->request->post());
$model->attributes = Yii::$app->request->post('User');
var_dump($model->attributes);

2Fix

Give the attribute a rule. If it needs no validation, mark it safe with the safe validator.

public function rules()
{
    return [
        [['name', 'email'], 'required'],
        [['bio', 'website'], 'safe'],
    ];
}

3Verify

Assign the post data again and dump the attributes. The field now holds the value.

var_dump($model->attributes);

Confirmed by yiiframework.com

Did this fix it?

Cause 3 of 4

The model is in a scenario where the attribute is not active

1Check

Massive assignment follows the scenario. If scenarios() lists the attributes for each scenario, only those listed for the current scenario are assigned. Rules that carry an on property apply only in that scenario.

var_dump($model->scenario);
var_dump($model->scenarios());

2Fix

Set the scenario before assigning data, and list the attribute in that scenario.

$model->scenario = User::SCENARIO_UPDATE;
$model->attributes = Yii::$app->request->post('User');

// in the model
public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios[self::SCENARIO_UPDATE] = ['name', 'email', 'bio'];
    return $scenarios;
}

3Verify

Dump the attributes and the errors again, then save.

var_dump($model->save(), $model->errors);

Confirmed by yiiframework.com

Did this fix it?

Cause 4 of 4

save() succeeds, but there is nothing to write

1Check

When save() updates a record, only dirty attributes are written: the ones changed since the record was loaded or saved. If your assignment sets the same values, or goes to another object, nothing changes.

var_dump($model->getDirtyAttributes());

2Fix

Assign the new values to the same model object that you call save() on, and make sure the values differ from the loaded ones.

$model = User::findOne($id);
$model->name = 'New name';
var_dump($model->getDirtyAttributes()); // ['name' => 'New name']
$model->save();

3Verify

Reload the row and compare.

var_dump(User::findOne($id)->name);

Confirmed by yiiframework.com

Did this fix it?

How do I stop it coming back?

  • Always handle a false result from save(). Log or show $model->errors instead of ignoring the return value.
  • Give every column a rule, even if it is only safe, so a new field is not dropped by massive assignment.
  • Name the scenario in the controller for each action, and keep scenarios() next to rules() in the model.
  • Write a small test that posts a valid form and checks the saved row.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

Apache returns 403 when a URL contains %3F

a request like /page%3Fname=test is refused while /page?name=test works

Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.

2 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.