Browse Source

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

Signed-off-by: Taylor Otwell <taylorotwell@gmail.com>
Taylor Otwell 12 years ago
parent
commit
17cabd47e6
1 changed files with 52 additions and 0 deletions
  1. 52 0
      laravel/database/eloquent/model.php

+ 52 - 0
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 @@ 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.
 	 *