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

[8.x] Allow caching to be disabled for virtual attributes accessors that return an object #40519

Merged
merged 7 commits into from Jan 20, 2022

Conversation

decnorton
Copy link
Contributor

Context: #40497

This PR allows caching to be disabled for virtual attributes being accessed used the new Attribute class method.

I often find myself adding virtual accessors to construct objects based on other attributes within the model, most commonly DateTime instances. Currently, the result of an accessor is cached if it's an object and only invalidated if the attribute's mutator is called. Scalar types are unaffected.

This PR adds a flag that will disable this behaviour. Mutating multiple attributes & value object casts will be unaffected by default.

Example

public function finish(): Attribute
{
    return Attribute::getWithoutCaching(fn () => $this->start->addSeconds($this->duration)));
}

or

public function finish(): Attribute
{
    return Attribute::get(fn () => $this->start->addSeconds($this->duration)))->disableObjectCaching();
}

@taylorotwell taylorotwell merged commit d5cfa87 into laravel:8.x Jan 20, 2022
@taylorotwell
Copy link
Member

Thanks for contributing to Laravel! ❤️

@RoodFruit
Copy link

@decnorton @taylorotwell shouldn't this be the default behavior of accessors (virtual attributes)? Why are they cached in the first place?

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.

None yet

3 participants