Skip to content

Instantly share code, notes, and snippets.

@atrakeur
Created June 18, 2014 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atrakeur/8aecd44aedbd50eada05 to your computer and use it in GitHub Desktop.
Save atrakeur/8aecd44aedbd50eada05 to your computer and use it in GitHub Desktop.
A simple way to add toObject ability to eloquent models. Usefull for generating stdClass objects instead of flat arrays.
<?php namespace Atrakeur\EnhancedModels;
use \stdClass;
abstract class EnhancedModel extends \Eloquent {
/*****************************************
* Act like toArray but generate stdClass objects on the current object.
*****************************************/
public function toObject()
{
return $this->convertToObject($this);
}
/*****************************************
* Act like toArray but generate stdClass objects on the given object.
*****************************************/
public function convertToObject($value)
{
if ($value instanceof \Eloquent)
{
$attributes = $value->toArray();
$relations = $value->relationsToArray();
$object = new stdClass();
foreach($attributes AS $key => $attribute)
{
if (array_key_exists($key, $relations))
{
$key = camel_case($key);
$object->$key = $this->convertToObject($value->$key);
}
else
{
$object->$key = $attribute;
}
}
return $object;
}
if ($value instanceof \Illuminate\Database\Eloquent\Collection)
{
$array = array();
foreach($value AS $key => $element)
{
$array[$key] = $this->convertToObject($element);
}
return $array;
}
return $value;
}
}
@DaveyBoyCrocky
Copy link

The recursive nature of this solution doesn't seem to work right when you have a relation that is a collection instead of a single object. I found I could get the results I wanted from:
json_decode($object->toJson())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment