Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property exists but property_exists() return false;

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']]);
}
like image 403
Danilo Kobold Avatar asked Mar 25 '17 00:03

Danilo Kobold


Video Answer


2 Answers

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.

like image 86
kjdion84 Avatar answered Nov 15 '22 12:11

kjdion84


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)
like image 40
fedeisas Avatar answered Nov 15 '22 14:11

fedeisas