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

Add hasAttribute() to Eloquent/Model #22249

Closed
wants to merge 2 commits into from

Conversation

johannesschobel
Copy link

This PR adds the hasAttribute() method to Eloquent/Model in order to check, if a given attribute exist in this model

This PR adds the `hasAttribute()` method to check, if a given attribute exist in this model
@taylorotwell
Copy link
Member

I would just suggest using isset($model->key).

@decadence
Copy link
Contributor

decadence commented Nov 29, 2017

@taylorotwell it returns false if attribute exists but has null value.

@johannesschobel
Copy link
Author

Actually, i think, isset($field) would have a different behavior.. Additionally, i think, it would be more laravelish to allow it to directly check it at the model itself by calling $model->hasAttribute(...)

@johannesschobel
Copy link
Author

@taylorotwell can you please re-open this PR and rethink it?

@johannesschobel
Copy link
Author

see this example here:

// let $user be a User model
$user->name = null;
dd(isset($user->name)); // false, even it is set!
dd($user->hasAttribute('name')); // true, even it is null

So i think, the isset(...) approach is not valid here..

@decadence
Copy link
Contributor

@johannesschobel Yes. That's what I write about. I think you should make another PR with this description because Taylor doesn't look on closed PRs.

@denis-chmel
Copy link

denis-chmel commented Jul 25, 2023

Need the same, and totally agree with @johannesschobel

// let $user be a User model
$user->name = null;
dd(isset($user->name)); // false, even it is set!
dd($user->hasAttribute('name')); // true, even it is null

I left a petition on change.org for @taylorotwell to merge this.

@royduin
Copy link
Contributor

royduin commented Jun 25, 2024

It's added in Laravel 11.3: #50909

@donnysim
Copy link
Contributor

@royduin it's still wrong because it will return true just because you have a cast or a mutator, which will never indicate that the attribute actually exists.

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.

6 participants