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

I have Laravel 5 red documentation and I saw that it supports json type fields in the database, but I noticed really strange 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 sow the database:

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

The 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 } } 

Pay attention to β€œin the field studies of answers”, and the β€œrotation” field that laravel generates for me is correctly structured and also a field of type json.

When I looked at phpMyAdmin, the value of the research field looks fine. (without\")

My server code for the response:

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

Am I correct database seed, or is the problem when I return the value on the server?

I know that I can solve this problem on the client side by removing the "\" characters, but this is my last option as it is not clean enough.

EDIT:

I solved this by adding an array to the Model class:

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

The documentation can be seen here.

+5
source share
1 answer

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 , and also convert the given array to JSON using the PHP json_encode function :

This way you convert the entire collection to json using json_encode() , which assumes your json field is a string and therefore avoided it.

+2
source

Source: https://habr.com/ru/post/1237461/


All Articles