Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix attribute mutators #470

Merged
merged 1 commit into from
Dec 11, 2024
Merged

Conversation

vencelkatai
Copy link
Contributor

Hi,

Issue

Since the latest version, attribute mutators of translated attributes are getting called twice when getting the translated value.
It is happening because the following change in PR #465 in the getTranslation method:

// if column value is `null` then we have nothing to do, return `null`
if (is_null(parent::getAttributeValue($key))) {
    return null;
}

parent::getAttributeValue will try to transform the value using the attribute, which causes it to be called with the raw value stored in the database.

It wouldn't be a big issue but in my case I have a translated date which I'd like to parse into Carbon.
For example:

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;

class Example extends Model
{
    use HasTranslations;

    public $translatable = ['date'];

    /** @return Attribute<Carbon, never> */
    public function date(): Attribute
    {
        return Attribute::get(fn ($value) => Carbon::parse($value));
    }
}

Getting the value raises an exception in this case:

$example = new Example();
$example->date = now();
$example->save();

$example->date; // Should be a Carbon object
Could not parse '{"en":"2024-12-10T20:01:47.992298Z"}'

I have added a simple test to reproduce the issue, you can see that it is getting called with the raw value first:
image

Fix

This PR solves this issue by using the untransformed value for the null check instead.

@freekmurze freekmurze merged commit fc3f318 into spatie:main Dec 11, 2024
19 checks passed
@freekmurze
Copy link
Member

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants