Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: decode JSON within Eloquent

Tags:

json

laravel

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();
}
like image 589
be-codified Avatar asked Jun 12 '15 13:06

be-codified


1 Answers

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.

like image 162
ceejayoz Avatar answered Oct 01 '22 12:10

ceejayoz