Created
June 18, 2014 20:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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())