Retrieving instances of models

This however does not allow for an easy way of checking if that particular user exists before using $user in the rest of your script. A better way:

if($user = User::find(40)){
// User exists
}

Specific models also have other ways of retrieving instances by other fields, e.g. User::getByEmail(). All models also have the static function findWith(), which allows you to do something like:

if($user = User::findWith('username', 'testuser'){
// User exists
}

Note that all of the above examples only return a single instance of a model.

Fields and attributes

All models have fields, standard values that each model carries. In our documentation, these are defined as properties. If you want to get all the field for a certain model, access the data property:

$user = new User(40);
print_r($user->data);

Most models (specifically, those that inherit AttributedModel, also allow for attributes. Attributes are arbitrary values that are saved as freeform key-value pairs along the model object. This allows us to store information specific to a certain module, without having to change the scheme of the model's database table.

attributes() returns all attributes for the model instance as a associative array.

is($key) returns a boolean based on if the attribute exists and if the model value is truthy (bool true, string 'true', int 1, string '1').

Property-style getters

The AttributedModel class also implements the magic method __get(), which makes it possible to write $user->attr('locale') as $user->locale to produce the same output.

Important to note, though:

Although gettting attributes as properties is possible, __set is not implemented, as that might cause mistakes. So $user->locale = 'something'; won't actually change the attribute value in the database!

Class Model also implements __get() for model fields, which always have precedence, so make sure not to use attributes key names that overlap with the names of model fields, as that might cause confusing results. An example:

Attribute values

Attribute values can contain any data type, as it will be serialized before inserting into the database. It is recommended, though, to not store class instances, as the class definition is required to exist everywhere this attribute might be unserialized. Arrays and instances of stdClass are completely fine though.