diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index 3d453a2b8ecb..0f46cc8696da 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -559,7 +559,7 @@ protected function getClassCastableAttributeValue($key) $caster = $this->resolveCasterClass($key); return $this->classCastCache[$key] = $caster instanceof CastsInboundAttributes - ? $this->attributes[$key] + ? ($this->attributes[$key] ?? null) : $caster->get($this, $key, $this->attributes[$key] ?? null, $this->attributes); } } diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index b3d2ccc4d77a..c2f5b6121e54 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -7,6 +7,7 @@ use DateTimeInterface; use Exception; use Foo\Bar\EloquentModelNamespacedStub; +use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Database\Connection; use Illuminate\Database\ConnectionResolverInterface; @@ -2068,6 +2069,14 @@ public function testGetOriginalCastsAttributes() $this->assertEquals(['foo' => 'bar'], $model->getOriginal('collectionAttribute')->toArray()); $this->assertEquals(['foo' => 'bar2'], $model->getAttribute('collectionAttribute')->toArray()); } + + public function testUnsavedModel() + { + $user = new UnsavedModel; + $user->name = null; + + $this->assertNull($user->name); + } } class EloquentTestObserverStub @@ -2493,3 +2502,16 @@ class EloquentModelWithUpdatedAtNull extends Model protected $table = 'stub'; const UPDATED_AT = null; } + +class UnsavedModel extends Model +{ + protected $casts = ['name' => Uppercase::class]; +} + +class Uppercase implements CastsInboundAttributes +{ + public function set($model, string $key, $value, array $attributes) + { + return is_string($value) ? strtoupper($value) : $value; + } +}