Framework: [Bug]?[Feature]? Custom model accessors not processed when ->toJson() called?

Created on 21 Jan 2013  路  5Comments  路  Source: laravel/framework

custom accessors only work when called directly.

ex: $model->zip normally returns a zip id from db (ex: 33)

custom accessor makes $model->zip return actual zip code (49505)

$model->toJson() returns value from db, and not custom accessor.

Seems to me like ->toJson() or ->toArray() should make use of the accessors without having to go through and manually re-build an array of the model to be returned

Most helpful comment

This is intentional and for performance reasons.

All 5 comments

In this particular case you really should use a default Eloquent relationship.

In order to force your attribute to be returned in the array, add it as a key to the $attributes array.

class User extends Eloquent {
    protected $attributes = array(
        'ZipCode' => '',
    );

    public function getZipCode()
    {
        return ....
    }
}

Note: this particular code sample is un tested but I've done this a few times. Should work. Relevant

the above code seems to make no difference when dumping the model ->toJson/Array

i can just build a custom json array to return for now

This is intentional and for performance reasons.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SachinAgarwal1337 picture SachinAgarwal1337  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments

klimentLambevski picture klimentLambevski  路  3Comments