Skip to content

Commit

Permalink
throw an exception if castable attribute was not retrieved
Browse files Browse the repository at this point in the history
  • Loading branch information
cosmastech committed Dec 22, 2023
1 parent 047edbc commit f33339b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
17 changes: 17 additions & 0 deletions tests/Database/DatabaseEloquentWithCastsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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.
*
Expand Down

0 comments on commit f33339b

Please sign in to comment.