From 17cabd47e6e9306863e0e9b3567ac6cbaa788761 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Thu, 29 Mar 2012 14:12:03 -0500 Subject: [PATCH] Added to_array() and $hidden variable to the Eloquent base model. Signed-off-by: Taylor Otwell --- laravel/database/eloquent/model.php | 52 +++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/laravel/database/eloquent/model.php b/laravel/database/eloquent/model.php index 763cd46f..0bcda60f 100644 --- a/laravel/database/eloquent/model.php +++ b/laravel/database/eloquent/model.php @@ -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 @@ final public function purge($key) 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. *