Please show some code :)
Why is update([$data]) on a date field not working?
Hi, I'm using a version of Laravel 7. I have defined a date column on my model's table using timestamp('custom_date') in the migration. I have added it to the $dates field of the model. When creating a new model (using Eloquent), I pass in a unix timestamp and the date is saved fine in the DB. However, when updating using Eloquent's update() function, I pass in the same unix timestamp and the date is saved something weird in the DB like -0001-11-30 00:00:00.
Creation of column (over two migrations unfortunately, forgot to make nullable first time):
Schema::table('model', function (Blueprint $table) {
$table->timestamp('custom_date');
});
Schema::table('model', function (Blueprint $table) {
DB::statement("ALTER TABLE model MODIFY COLUMN custom_date TIMESTAMP NULL AFTER content");
DB::statement("UPDATE model SET custom_date = NULL");
});
Sample $data (works fine for creation and with workaround):
$data = [
'content' => 'Lorem ipsum',
'custom_date' => 1600865316
];
Model.php has:
protected $fillable = ['content', 'custom_date'];
protected $dates = ['custom_date'];
Repository functions, with update that doesn't work as expected (for the date only):
public function create($data)
{
$model = Model::create($data);
return $model;
}
public function update($id, $data)
{
// here I verified that if I make a Carbon object from the timestamp, like so-
// Carbon::createFromTimestamp($data['custom_date']);
// and dd or codecept_debug it, it is the correct date,
// though it is saved wrong in the db.
// Docs states that timestamp should work, and it works for create.
return Model::where('id', $id)->update($data);
}
I have verified that the timestamp converts to a valid and correct Carbon object. I have found a workaround, which is to set that attribute directly, save() the model instance, and then unset that field before the update().
Workaround:
public function update($id, $data)
{
$model = Model::find($id);
$model->custom_date = $data['custom_date'];
$model->save();
unset($data['custom_date']);
return Model::where('id', $id)->update($data);
}
However it seems odd and this behaviour isn't mentioned anywhere in the docs (that I could find). Is this a bug or am I missing something?
Please or to participate in this conversation.