Laravel 4 - How to json_decode a field every time its accessed?

json, laravel, laravel-4, php

Solution

Use an Eloquent accessor on your model:

public function getPreferencesAttribute($value)
{
    return json_decode($value);
}

And then you just have to:

$user = User::find($id);

return $user->preferences;

Look at the docs: http://laravel.com/docs/eloquent#accessors-and-mutators

Problem

We are storing User preferences as JSON. Since our application acts as an API, responses are returned as JSON as well, but the preferences field is returned as a string. I'd like to make sure this portion of the object is always decoded before any response is sent ie ``` $user->prefs = json_decode($user->prefs); ``` But where? Should I look at "overloading" the User index method? Is this more of a before_filter action? What is laravel way of doing this?

Original source