From 0b0a643d9768fc9b0f60121aa112a932ff623e2e Mon Sep 17 00:00:00 2001 From: lazerg Date: Wed, 29 Jul 2026 04:56:11 +0500 Subject: [PATCH] [13.x] Fix appended accessors receiving null in toArray() --- .../Eloquent/Concerns/HasAttributes.php | 2 +- tests/Database/DatabaseEloquentModelTest.php | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index 075113972995..702e7a9d66a4 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -246,7 +246,7 @@ public function attributesToArray() // as these attributes are not really in the attributes array, but are run // when we need to array or JSON the model for convenience to the coder. foreach ($this->getArrayableAppends() as $key) { - $attributes[$key] = $this->mutateAttributeForArray($key, null); + $attributes[$key] = $this->mutateAttributeForArray($key, $this->getAttributeFromArray($key)); } return $attributes; diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index 8300d8c81ac7..b37d90176d0f 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -2566,6 +2566,15 @@ public function testAppendingOfAttributes() $this->assertSame([], $model->toArray()); } + public function testToArrayPassesRealValueToAppendedAccessor() + { + $model = new EloquentModelAppendsWithExistingAttributeStub; + $model->price = 100; + + $this->assertSame(100, $model->price); + $this->assertSame(100, $model->toArray()['price']); + } + public function testMergeAppendsMergesAppends() { $model = new EloquentModelAppendsStub; @@ -4307,6 +4316,18 @@ public function getStudlyCasedAttribute() } } +class EloquentModelAppendsWithExistingAttributeStub extends Model +{ + protected $guarded = []; + + protected $appends = ['price']; + + protected function price(): Attribute + { + return Attribute::get(fn ($value) => $value); + } +} + class EloquentModelGetMutatorsStub extends Model { public static function resetMutatorCache()