11

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();
}

1 Answer 1

39

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Is attribute casting possible with DB class?
@Zigson No, but you should avoid direct DB calls if at all possible. You lose the benefits of things like soft deletes, relationships, etc.
Thank you for your reply. I will see what can I do.
You should not have to necessarily avoid direct DB calls. Eloquent makes query a lot slower then when you are using the DB query builder. When you need performance, you should ditch Eloquent and write the queries yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.