From f33339b6b64357ba884a6c5bef9a9aed5e6478fa Mon Sep 17 00:00:00 2001 From: Luke Kuzmish Date: Fri, 22 Dec 2023 06:49:57 -0500 Subject: [PATCH] throw an exception if castable attribute was not retrieved --- .../Eloquent/Concerns/HasAttributes.php | 3 +++ .../Database/DatabaseEloquentWithCastsTest.php | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index 8385eef4eea9..760fee05bec2 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -2126,6 +2126,9 @@ protected function transformModelValue($key, $value) // an appropriate native PHP type dependent upon the associated value // given with the key in the pair. Dayle made this comment line up. if ($this->hasCast($key)) { + if (! array_key_exists($key, $this->attributes)) { + $this->throwMissingAttributeExceptionIfApplicable($key); + } return $this->castAttribute($key, $value); } diff --git a/tests/Database/DatabaseEloquentWithCastsTest.php b/tests/Database/DatabaseEloquentWithCastsTest.php index 53fe7d449d70..42df77184e05 100644 --- a/tests/Database/DatabaseEloquentWithCastsTest.php +++ b/tests/Database/DatabaseEloquentWithCastsTest.php @@ -3,6 +3,8 @@ namespace Illuminate\Tests\Database; use Illuminate\Database\Capsule\Manager as DB; +use Illuminate\Database\Eloquent\MissingAttributeException; +use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model as Eloquent; use PHPUnit\Framework\TestCase; @@ -76,6 +78,21 @@ public function testWithCreateOrFirst() $this->assertSame($time1->id, $time2->id); } + public function testThrowsExceptionWhenPrevents() + { + Time::create(['time' => now()]); + $originalMode = Model::preventsAccessingMissingAttributes(); + Model::preventAccessingMissingAttributes(); + + $this->expectException(MissingAttributeException::class); + try { + $time = Time::query()->select('id')->first(); + $this->assertNull($time->time); + } finally { + Model::preventAccessingMissingAttributes($originalMode); + } + } + /** * Get a database connection instance. *