Akhil F
Akhil F

Reputation: 7740

Whats the right way to store JSON in a database with Laravel?

I have JSON data I want to store in a database. Ideally, the data should be automatically decoded when I retreive from the database and automatically encoded when I store in the database.

How can I do this?

Upvotes: 0

Views: 316

Answers (1)

marcanuy
marcanuy

Reputation: 23962

Use Accessors and Mutators, for an attribute called foobar add these two functions in your Eloquent model:

public function getFoobarAttribute($value){
    return json_decode($value);
}
public function setFoobarAttribute($value){
    $this->attributes['foobar'] = json_encode($value);
}

Upvotes: 1

Related Questions