diff --git a/src/Database/Model.php b/src/Database/Model.php index ae8a5d251..0ba5402eb 100644 --- a/src/Database/Model.php +++ b/src/Database/Model.php @@ -1174,6 +1174,7 @@ public function hasGetMutator($key) public function attributesToArray() { $attributes = $this->getArrayableAttributes(); + $mutatedAttributes = $this->getMutatedAttributes(); /* * Before Event @@ -1184,55 +1185,12 @@ public function attributesToArray() } } - /* - * Dates - */ - foreach ($this->getDates() as $key) { - if (!isset($attributes[$key])) { - continue; - } - - $attributes[$key] = $this->serializeDate( - $this->asDateTime($attributes[$key]) - ); - } - - /* - * Mutate - */ - $mutatedAttributes = $this->getMutatedAttributes(); - - foreach ($mutatedAttributes as $key) { - if (!array_key_exists($key, $attributes)) { - continue; - } - - $attributes[$key] = $this->mutateAttributeForArray( - $key, - $attributes[$key] - ); - } + $attributes = $this->addDateAttributesToArray($attributes); - /* - * Casts - */ - foreach ($this->casts as $key => $value) { - if ( - !array_key_exists($key, $attributes) || - in_array($key, $mutatedAttributes) - ) { - continue; - } + $attributes = $this->addMutatedAttributesToArray($attributes, $mutatedAttributes); - $attributes[$key] = $this->castAttribute( - $key, - $attributes[$key] - ); - } + $attributes = $this->addCastAttributesToArray($attributes, $mutatedAttributes); - /* - * Appends - */ foreach ($this->getArrayableAppends() as $key) { $attributes[$key] = $this->mutateAttributeForArray($key, null); } diff --git a/tests/Database/ModelTest.php b/tests/Database/ModelTest.php index a5cb2021f..63f7422db 100644 --- a/tests/Database/ModelTest.php +++ b/tests/Database/ModelTest.php @@ -470,6 +470,35 @@ public function testAddCasts() $this->assertEquals(['id' => 'int', 'foo' => 'int'], $model->getCasts()); } + public function testAddDatesCasts() + { + $model = new TestModelGuarded(); + $model->timestamps = false; + + $model->addCasts([ + 'created_at' => 'date:Y/m/d', + 'updated_at' => 'datetime:Y_m_d @ H:i', + 'deleted_at' => 'date', + ]); + + $model->created_at = '2025-10-31 22:50:55'; + $model->updated_at = '2025-12-31 23:59:59'; + $model->deleted_at = '2026-01-01 12:13:14'; + + $this->assertInstanceOf(\Winter\Storm\Argon\Argon::class, $model->created_at); + $this->assertInstanceOf(\Winter\Storm\Argon\Argon::class, $model->updated_at); + $this->assertInstanceOf(\Winter\Storm\Argon\Argon::class, $model->deleted_at); + + $this->assertEquals( + [ + 'created_at' => '2025/10/31', + 'updated_at' => '2025_12_31 @ 23:59', + 'deleted_at' => '2026-01-01T00:00:00.000000Z', + ], + $model->attributesToArray() + ); + } + public function testStringIsTrimmed() { $name = "Name";