I'm going to propose a solution here. Disclaimer here that I have not tested the code, but the approach is very similar to what I'm looking to implement in the next few days (refomatting Eloquent results for Ember.js compatibility).
Basically what Taylor Otwell (creator of Laravel) suggested is:
Check out the "newCollection" method on the Eloquent\Model class. Override that in a base model and return a custom collection that extends Illuminate\Database\Eloquent\Collection. Then in that Collection extension override the toArray method to format stuff how you want.
So in theory you could do these three steps:
- Create a subclass of
Illuminate\Database\Eloquent\Collection
and override the toArray()
to do RJSON formatting before returning. Let's say call it RJsonCollection
.
- Create a subclass of
Illuminate\Database\Eloquent\Model
to override newCollection()
method to use your new RJsonCollection
subclass. Let's say call it BaseModel
.
- Convert your models to extend the new
BaseModel
.
Something like this:
app/models/RJsonCollection.php:
<?php
class RJsonCollection extends Illuminate\Database\Eloquent\Collection
{
public function toArray()
{
$parentArray = parent::toArray();
return Dmitrirussu\RJson::pack($parentArray);
}
}
Note that I'm assuming based on your question's code that Dmitrirussu\RJson::pack($parentArray)
will return a collection/array. You may need to adjust the code above and make sure it returns the proper RJSON array.
app/models/BaseModel.php:
<?php
class BaseModel extends Eloquent
{
public function newCollection(array $models = array())
{
return new RJsonCollection($models);
}
}
app/models/UserModel.php:
<?php
class UserModel extends BaseModel
{
// ...
}
And of course the usual composer dump-autoload
and stuff when creating new classes. You may notice that I put all classes above in the models folder and no namespacing. Not the best practices but they do help keeping the example simple and straightforward.