diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index 05769a50f1d7..1654e39b12b7 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -527,10 +527,7 @@ public function setAttribute($key, $value) } if ($this->isJsonCastable($key) && ! is_null($value)) { - $value = $this->asJson($value); - if (false === $value) { - throw JsonEncodingException::forAttribute($key, json_last_error_msg()); - } + $value = $this->castAttributeAsJson($key, $value); } // If this attribute contains a JSON ->, we'll set the proper value in the @@ -613,6 +610,26 @@ protected function getArrayAttributeByKey($key) $this->fromJson($this->attributes[$key]) : []; } + /** + * Cast the given attribute to JSON. + * + * @param string $key + * @param mixed $value + * @return string + */ + protected function castAttributeAsJson($key, $value) + { + $value = $this->asJson($value); + + if ($value === false) { + throw JsonEncodingException::forAttribute( + $this, $key, json_last_error_msg() + ); + } + + return $value; + } + /** * Encode the given value as JSON. * diff --git a/src/Illuminate/Database/Eloquent/JsonEncodingException.php b/src/Illuminate/Database/Eloquent/JsonEncodingException.php index a31b03df8907..5878b0f7b7e3 100644 --- a/src/Illuminate/Database/Eloquent/JsonEncodingException.php +++ b/src/Illuminate/Database/Eloquent/JsonEncodingException.php @@ -21,12 +21,15 @@ public static function forModel($model, $message) /** * Create a new JSON encoding exception for an attribute. * + * @param mixed $model * @param mixed $key * @param string $message * @return static */ - public static function forAttribute($key, $message) + public static function forAttribute($model, $key, $message) { - return new static('Error encoding value of attribute ['.$key.'] to JSON: '.$message); + $class = get_class($model); + + return new static("Unable to encode attribute [{$key}] for model [{$class}] to JSON: {$message}."); } } diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index 91bee7c9605c..55ce683559b5 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -1468,7 +1468,6 @@ public function testModelAttributeCastingPreservesNull() /** * @expectedException \Illuminate\Database\Eloquent\JsonEncodingException - * @expectedExceptionMessage Error encoding value of attribute */ public function testModelAttributeCastingFailsOnUnencodableData() {