Q:

Access keys in json type column for Eloquent collections?

A table column in my database is saved as json type. I want to display a keyed value in the saved json object on my blade templates but I'm unsure how.
Let's say I have $table->json('meta') in my table schema for Newsletter model, with meta column having e.g. {"foo": "bar"} as value.
How would I retrieve something like $newsletter->meta->foo? Since $newsletter->meta returns string instead of json object by default on Laravel 5.5 requiring a trivial json_decode to convert it.
A cleaner solution besides json_decode on every call, would be to use an accessor on that column e.g. getMetaAttribute but that's still messy. I want automatic json column to PHP object detection, how can I make this happen?

A:

You can declare a protected $casts array inside your model in which you can instruct Eloquent to automatically convert types of model attributes. In your case that would look like this:
/*
 * @property string $meta - json is actually just a string
 */
class Newsletter extends Model {

    protected $casts = [
        'meta' => 'array',
    ];
}

// Now you can use `$meta` as array:
$newsletter = Newsletter::find(1);
$foo = array_get($newsletter->meta, 'foo');

But this still does not convert it into an object. Although object is mentioned in the docs as being a valid cast type, I can not tell you exactly what it does.
As a note, these $casts are not bi-directional. If you want to set meta on a Newsletter instance, you'd have to create your own facilities to convert any object or array into a json string. Eloquent allows you to define mutators on your model to get the job done.

