Well I'm really confused. When i check if a property exists it returns false.
if (property_exists($pais, 'id'))
// false
but when I debug it shows me it's there.
print_r($pais->id);
// 1
print_r(property_exists($pais, 'id'));
// false
Am I crazy or my neurons just fried?
and the creation of pais is done by
if (key_exists('country', $data))
$pais = Pais::adicionarPais($data);
(...)
public static function adicionarPais(array $data)
{
return Pais::firstOrCreate(['nome' => $data['country']]);
}
You can convert the model to an array and then use array_key_exists
. Eloquent object properties are set via magic methods, so property_exists
will not work, especially if the property actually does exist but is set to null
.
Example:
$pais = Pais::find(1);
if (array_key_exists('country', $pais->toArray())) {
// do stuff
}
Note the use of toArray
on the model.
I see you're using Laravel, so I guess this are Eloquent models. They're probably using magic methods to create dynamic properties and methods from your database columns. Take a look here: http://php.net/manual/en/language.oop5.overloading.php
So, instead of having real properties, every time you request a property, they will check if there's any column or relationship and return that instead.
You can get your model attributes with the getAttributes()
method (https://github.com/illuminate/database/blob/master/Eloquent/Concerns/HasAttributes.php#L851)
class Pais
{
public function __get($name) {
if ($name == 'id') {
return 1;
}
}
}
$pais = new Pais();
var_dump($pais->id); // int(1)
var_dump(property_exists($pais, 'id')); // bool(false)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With