Reputation: 6124
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
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_encode
ing your data if you use casts, as Laravel will now do that step automatically as well.
Upvotes: 39