be-codified
be-codified

Reputation: 6124

Laravel: decode JSON within Eloquent

I need to JSON decode a certain column in my Eloquent query. Is there a way to do this without breaking all apart?

So far I have this.

public function index()
{
    return Offer::all();
}

Upvotes: 11

Views: 22285

Answers (1)

ceejayoz
ceejayoz

Reputation: 180014

Use an accessor on the model:

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

or use attribute casting to tell Laravel to do it automatically:

protected $casts = [
    'column_name' => 'array',
];

The array cast type is particularly useful when working with columns that are stored as serialized JSON.

Note that you may have to stop json_encodeing your data if you use casts, as Laravel will now do that step automatically as well.

Upvotes: 39

Related Questions