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

Inbound custom cast generates PHP notices when setting values to null on new model instances #32111

Closed
wfeller opened this issue Mar 25, 2020 · 3 comments · Fixed by #32118
Closed
Labels

Comments

@wfeller
Copy link
Contributor

wfeller commented Mar 25, 2020

  • Laravel Version: 7.3.0
  • PHP Version: 7.4.3
  • Database Driver & Version: n/a

Description:

When using inbound custom casts, and setting a value to null on an empty model, we get PHP notices of undefined index.

Setting a null initial value will try to retrieve the current value by doing $this->attributes[$key], but since $this->attributes[$key] does not exist yet, we get a PHP notice.

In HasAttributes->getClassCastableAttributeValue(), it can be solved by changing the following:

   return $this->classCastCache[$key] = $caster instanceof CastsInboundAttributes
                ? $this->attributes[$key]
                : $caster->get($this, $key, $this->attributes[$key] ?? null, $this->attributes);

Into:

   return $this->classCastCache[$key] = $caster instanceof CastsInboundAttributes
                ? ($this->attributes[$key] ?? null)
                : $caster->get($this, $key, $this->attributes[$key] ?? null, $this->attributes);

Steps To Reproduce:

class User extends Authenticatable
{
    protected $casts = ['name' => Uppercase::class];
}
class Uppercase implements CastsInboundAttributes
{
    public function set($model, string $key, $value, array $attributes)
    {
        return is_string($value) ? strtoupper($value) : $value;
    }
}
$user = new User;
$user->name = null;

image

@driesvints driesvints added the bug label Mar 26, 2020
@driesvints
Copy link
Member

Indeed seems a bug to me. Can you send in a PR?

@driesvints
Copy link
Member

driesvints commented Mar 26, 2020

I sent in a pr: #32118

@wfeller
Copy link
Contributor Author

wfeller commented Mar 26, 2020

Thanks!

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

Successfully merging a pull request may close this issue.

2 participants