Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel database with json type field adds \" when returning value

I've red the Laravel 5 documentation, and I've seen that it supports json type fields in database, but I've noticed really weird behavior.

This is my table:

Schema::create('subjects', function ($table) {
        $table->increments('id');
        $table->string('name', 100);
        $table->integer('ects');

        $table->json('studies'); // this is my json type field

        $table->date('created_at');
        $table->date('updated_at');
});

Then I seed the database with:

Subject::create(['name' => 'Programming 1', 
'ects' => '0',
'studies' => '{"program":"Computer Science","year":"1"}']);

Server response looks something like this:

{
     "id": 15,
     "name": "Programming 1",
     "brEcts": 0,
     "studies": "{\"program\":\"Computer Science\",\"year\":\"1\"}",
     "created_at": "2015-12-05 00:00:00",
     "updated_at": "2015-12-05 00:00:00",
     "pivot": {
         "profesor_id": 20,
         "subject_id": 15
     }
}

Notice the \" in response field studies, and the "pivot" field that laravel generated for me is correctly structured, and is also json type field.

When I looked into phpMyAdmin, value of studies field looks normal. (without \")

My server code for response:

$subjects = Profesor::find($id)->subjets()->get();
return response()->json($subjects);

Did I seed the database correctly, or the problem is when I return value on server?

I know that I can solve this problem on client side deleting symbols "\" but that is my last option since its not clean enough.

EDIT:

I solved it by adding an array casts in my Model class:

protected $casts = [
     'name' => 'string',
     'ects' => 'integer',
     'studies' => 'array'
];

Documentation can be seen here

like image 718
Andrej Avatar asked Oct 31 '22 14:10

Andrej


1 Answers

It looks like you are json encoding the entire eloquent collection, which is returned when you use the get() method (http://laravel.com/docs/5.1/eloquent-collections).

From the laravel docs:

The json method will automatically set the Content-Type header to application/json, as well as convert the given array into JSON using the json_encode PHP function:

So essentially, you are converting the entire collection to json using json_encode() which will assume that your json field is a string and has therefore escaped it.

like image 193
craig_h Avatar answered Nov 09 '22 14:11

craig_h