Commit 17cabd47 authored by Taylor Otwell's avatar Taylor Otwell

Added to_array() and $hidden variable to the Eloquent base model.

Signed-off-by: 's avatarTaylor Otwell <taylorotwell@gmail.com>
parent 023dacf5
......@@ -55,6 +55,13 @@ abstract class Model {
*/
public static $accessible;
/**
* The attributes that should be excluded from to_array.
*
* @var array
*/
public static $hidden = array();
/**
* Indicates if the model has update and creation timestamps.
*
......@@ -520,6 +527,51 @@ abstract class Model {
unset($this->attributes[$key]);
}
/**
* Get the model attributes and relationships in array form.
*
* @return array
*/
public function to_array()
{
$attributes = array();
// First we need to gather all of the regular attributes. If the attribute
// exists in the array of "hidden" attributes, it will not be added to
// the array so we can easily exclude things like passwords, etc.
foreach (array_keys($this->attributes) as $attribute)
{
if ( ! in_array($attribute, static::$hidden))
{
$attributes[$attribute] = $this->$attribute;
}
}
foreach ($this->relationships as $name => $models)
{
// If the relationship is not a "to-many" relationship, we can just
// to_array the related model and add it as an attribute to the
// array of existing regular attributes we gathered.
if ( ! is_array($models))
{
$attributes[$name] = $models->to_array();
}
// If the relationship is a "to-many" relationship we need to spin
// through each of the related models and add each one with the
// to_array method, keying them both by name and ID.
else
{
foreach ($models as $id => $model)
{
$attributes[$name][$id] = $model->to_array();
}
}
}
return $attributes;
}
/**
* Handle the dynamic retrieval of attributes and associations.
*
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment