-
Notifications
You must be signed in to change notification settings - Fork 11.1k
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
Add hasAttribute method to Eloquent Models #44717
Add hasAttribute method to Eloquent Models #44717
Conversation
Can you do |
Isset indeed works for Attributes, GetMutators, Relations, and AttributeMutators. Sadly isset does not work for Castables. |
Why would if (array_key_exists($key, $this->casts)) {
return true;
} mean the attribute exists? This will result in always returning true because a cast exists even though the attribute wasn't selected - doesn't exist. |
@donnysim I guess if a casts exists, the model must has that attribute at some point. Even if that means that that the attribute is null or still has no allocated value at all. |
But isn't the whole point of hasAttribute to check if it exists now not if it will exist at some point? Because what does it actually solve then? It will say true and the next thing you get will be a missing attribute exception because it lied? |
If there is a cast no missingAttributException will be thrown. The |
Oh, so the whole attribute strict mode is even more crooked than I imagined 😂. It shouldn't matter if a cast is defined or not, if the attribute does not exist for casting it should throw an error. Isn't it the whole point of it? class TestModel extends Model
{
protected $casts = [
'parent_id' => 'int',
];
}
TetsModel::first(['id'])->parent_id // <- should throw not silently return null Sadly the more I follow the whole strict mode changes the more I'm inclined to just never use the built in way because it's a minefield in itself, so I'll just leave you do your things and carry on. |
This PR is not a general discussion regarding Laravel's strict mode. |
Personally, I think that Either way, I don't think |
I honestly am not sure I plan to mess with this anymore. I'm not super happy with how "strict mode" has panned out and it has felt a bit more trouble than it's worth. |
It's added in Laravel 11.3: #50909 |
Hello Laravel Team,
With Laravel's new strict
Model::preventAccessingMissingAttributes
Eloquent configuration, there are some problems with 3rd party packages when these packages want to access optional attributes.To prevent
MissingAttributeException
, it would be handy to have a central way to check if an Eloquent Model attribute exists or not.This PR introduces a new
hasAttribute(string $key): bool
method on Eloquent models to check if a model has an attribute configured. This also could be archived in the 3rd party package code. But I think it would be helpful if this gets added to the core. So it will be aligned with upcoming new framework features.