Skip to content

Commit 0138d78

Browse files
authored
fix: prevent casting empty string to array from triggering json error (#52415)
1 parent 763b942 commit 0138d78

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1271,7 +1271,11 @@ protected function asJson($value)
12711271
*/
12721272
public function fromJson($value, $asObject = false)
12731273
{
1274-
return Json::decode($value ?? '', ! $asObject);
1274+
if ($value === null || $value === '') {
1275+
return null;
1276+
}
1277+
1278+
return Json::decode($value, ! $asObject);
12751279
}
12761280

12771281
/**

tests/Database/DatabaseConcernsHasAttributesTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,14 @@ public function testWithConstructorArguments()
2121
$attributes = $instance->getMutatedAttributes();
2222
$this->assertEquals(['some_attribute'], $attributes);
2323
}
24+
25+
public function testCastingEmptyStringToArrayDoesNotError()
26+
{
27+
$instance = new HasAttributesWithArrayCast();
28+
$this->assertEquals(['foo' => null], $instance->attributesToArray());
29+
30+
$this->assertTrue(json_last_error() === JSON_ERROR_NONE);
31+
}
2432
}
2533

2634
class HasAttributesWithoutConstructor
@@ -40,3 +48,23 @@ public function __construct($someValue)
4048
{
4149
}
4250
}
51+
52+
class HasAttributesWithArrayCast
53+
{
54+
use HasAttributes;
55+
56+
public function getArrayableAttributes(): array
57+
{
58+
return ['foo' => ''];
59+
}
60+
61+
public function getCasts(): array
62+
{
63+
return ['foo' => 'array'];
64+
}
65+
66+
public function usesTimestamps(): bool
67+
{
68+
return false;
69+
}
70+
}

0 commit comments

Comments
 (0)