Yii2 $model->save() returns false or saves nothing, with no error shown
$model->save() returns false and no row is writtenShort 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.
Fix it fast
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();2Match what you see, then jump to its fix
- 1
save() 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
The 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
The 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
save() returns true, and the table row still has the old valuessave() succeeds, but there is nothing to writeFix
- 1
What does the error look like?
$model->save() returns false and no row is writtensave() returns true, but the database row did not changeA 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
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
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
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
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
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack 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 fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix