diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index d5f8225cf1bc..557a36b90448 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -165,6 +165,13 @@ trait HasAttributes */ protected static $setAttributeMutatorCache = []; + /** + * The cache of the converted cast types. + * + * @var array + */ + protected static $castTypeCache = []; + /** * The encrypter instance that is used to encrypt attributes. * @@ -818,19 +825,23 @@ protected function getEnumCastableAttributeValue($key, $value) */ protected function getCastType($key) { - if ($this->isCustomDateTimeCast($this->getCasts()[$key])) { - return 'custom_datetime'; - } + $castType = $this->getCasts()[$key]; - if ($this->isImmutableCustomDateTimeCast($this->getCasts()[$key])) { - return 'immutable_custom_datetime'; + if (isset(static::$castTypeCache[$castType])) { + return static::$castTypeCache[$castType]; } - if ($this->isDecimalCast($this->getCasts()[$key])) { - return 'decimal'; + if ($this->isCustomDateTimeCast($castType)) { + $convertedCastType = 'custom_datetime'; + } elseif ($this->isImmutableCustomDateTimeCast($castType)) { + $convertedCastType = 'immutable_custom_datetime'; + } elseif ($this->isDecimalCast($castType)) { + $convertedCastType = 'decimal'; + } else { + $convertedCastType = trim(strtolower($castType)); } - return trim(strtolower($this->getCasts()[$key])); + return static::$castTypeCache[$castType] = $convertedCastType; } /** @@ -882,8 +893,8 @@ protected function isCustomDateTimeCast($cast) */ protected function isImmutableCustomDateTimeCast($cast) { - return strncmp($cast, 'immutable_date:', 15) === 0 || - strncmp($cast, 'immutable_datetime:', 19) === 0; + return str_starts_with($cast, 'immutable_date:') || + str_starts_with($cast, 'immutable_datetime:'); } /** @@ -1491,11 +1502,13 @@ protected function isEncryptedCastable($key) */ protected function isClassCastable($key) { - if (! array_key_exists($key, $this->getCasts())) { + $casts = $this->getCasts(); + + if (! array_key_exists($key, $casts)) { return false; } - $castType = $this->parseCasterClass($this->getCasts()[$key]); + $castType = $this->parseCasterClass($casts[$key]); if (in_array($castType, static::$primitiveCastTypes)) { return false; @@ -1516,11 +1529,13 @@ protected function isClassCastable($key) */ protected function isEnumCastable($key) { - if (! array_key_exists($key, $this->getCasts())) { + $casts = $this->getCasts(); + + if (! array_key_exists($key, $casts)) { return false; } - $castType = $this->getCasts()[$key]; + $castType = $casts[$key]; if (in_array($castType, static::$primitiveCastTypes)) { return false;