Closed hubertnnn closed 5 months ago
Here is my use case: In database I have a keep_updated column. In my model I have following attribute:
keep_updated
protected function keepUpdated(): Attribute { return Attribute::make( get: fn($value) => json_decode($value) ?? [], set: fn($value) => json_encode($value), ); }
If my database contains two rows with values null and ["test"], then this gives me following output:
null
["test"]
$deployment = ProjectDeployment::find(121); dump($deployment->keepUpdated); dump($deployment->keep_updated); $deployment = ProjectDeployment::find(122); dump($deployment->keepUpdated); dump($deployment->keep_updated);
null // app/Http/Controllers/TestController.php:13 [] // app/Http/Controllers/TestController.php:14 null // app/Http/Controllers/TestController.php:17 array:1 [▼ // app/Http/Controllers/TestController.php:18 0 => "test" ]
After switching to using a Cast class I get following (correct) result:
class AsArray implements CastsAttributes { public function get($model, string $key, $value, array $attributes) { return json_decode($value) ?? []; } public function set($model, string $key, $value, array $attributes) { return json_encode($value); } }
[] // app/Http/Controllers/TestController.php:13 [] // app/Http/Controllers/TestController.php:14 array:1 [▼ // app/Http/Controllers/TestController.php:17 0 => "test" ] array:1 [▼ // app/Http/Controllers/TestController.php:18 0 => "test" ]
It seems that Eloquence does not work correctly with Laravel Attributes possibly because of the if (method_exists($this, $key)) { line that will detect the attribute as relationship and use wrong method.
if (method_exists($this, $key)) {
I'll need to take a closer look into this one - haven't yet played with attributes.
@hubertnnn I think this is now fixed on v11, let me know.
Here is my use case: In database I have a
keep_updated
column. In my model I have following attribute:If my database contains two rows with values
null
and["test"]
, then this gives me following output:After switching to using a Cast class I get following (correct) result:
It seems that Eloquence does not work correctly with Laravel Attributes possibly because of the
if (method_exists($this, $key)) {
line that will detect the attribute as relationship and use wrong method.