Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent retrieve row with JSON column

I have following data in my table

Table:

id    |name   | option_data

1     |Joe    |{"gender":"Male","cnic":"1234567","dob":"2016-03-14"}     
2     |Doe    |{"gender":"Male","cnic":"9999","dob":"2016-03-14"}     

How can I get data in proper json_encode format.

For example if I write

echo json_encode($app->auth->users);

My Output for option_data

option_data":"{\"gender\":\"Male\",\"cnic\":\"61101-6859110-3\",\"dob\":\"2016-03-14\"}"

My database column type is Text. If I remove all \ using stripslashes still data is not a valid JSON because its wrapped in " double qoutes.

Question

How can I get data in proper json_encode format with all other coulmns.

like image 536
Nomi Avatar asked May 16 '16 19:05

Nomi


1 Answers

You can just use $casts variable in your model and it will automatically convert to json and reverse to array.

protected $casts = [
     "option_data" => "array"
];
like image 129
Vahan Gevorgyan Avatar answered Nov 14 '22 23:11

Vahan Gevorgyan