kirkbushell / eloquence

A drop-in library for certain database functionality in Laravel, that allows for extra features that may never make it into the main project.
MIT License
537 stars 60 forks source link

Eloquence does not work correctly when using Laravel Attributes #102

Closed hubertnnn closed 5 months ago

hubertnnn commented 1 year ago

Here is my use case: In database I have a keep_updated column. In my model I have following attribute:

    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:

        $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.

kirkbushell commented 10 months ago

I'll need to take a closer look into this one - haven't yet played with attributes.

kirkbushell commented 5 months ago

@hubertnnn I think this is now fixed on v11, let me know.