Gianmarco Gagliardi
Gianmarco Gagliardi

Reputation: 512

JSON Columns in API Laravel Add not insert

when I go to do the "add" via POST the json is not inserted. I would like to insert in the "paramJson" column a json via api / polls. but it gives me problems

I have the following fields:

public function up()
        {
            Schema::create('polls', function (Blueprint $table) {
                $table->id();
                $table->text('now');
                $table->json('paramJson');
                $table->enum('status', ['a', 'b', 'c','d'])->default('a');
            });
        }

Poll model:

protected $fillable=[
        'now',
    ];

protected $casts = [
        'paramJson' => 'array',
    ];

PollsController.php

public function add(Request $request)
    {
        $poll = Poll::create($request->all());
        return response()->json($poll, 201);
    }

Route API

Route::post('polls','PollsController@add');

I make the post call http://127.0.0.1:8000/api/polls. where I send a json as follows:

{
 "now": "did the MJ12 exist?",
 "paramJson" : "{"key1": "value1", "key2": "value2"}"
}

gives the following error: SQLSTATE[HY000]: General error: 1364

while if I insert it so it takes it:

{
 "now": "did the MJ12 exist?",
 "paramJson" : "{\"key1\": \"value1\", \"key2\": \"value2\"}"
}

SQLSTATE[HY000]: General error: 1364 Field 'paramJson'

while if I insert it from DB I see it like this

INSERT INTO polls (now, paramJson) values ("did the MJ12 exist?", '{"key1": "value1", "key2": "value2"}') 

"paramJson":"{\"key1\": \"value1\", \"key2\": \"value2\"}",

it is not possible to insert a json in laravel like this?

Upvotes: 2

Views: 522

Answers (2)

Gianmarco Gagliardi
Gianmarco Gagliardi

Reputation: 512

i change

Poll model:

protected $fillable=[
                'now',
           'paramJson',
            ];
protected $casts = [
                'paramJson' => 'array',
            ];

it works

Upvotes: 0

dewd
dewd

Reputation: 4429

It looks like your JSON is encoded incorrectly. Try:

{
 "now": "did the MJ12 exist?",
 "paramJson" : {
     "key1": "value1", 
     "key2": "value2"
 }
} 

ie leave double quotes off the value of paramJson. {"key1": "value1", "key2": "value2"} not "{"key1": "value1", "key2": "value2"}"

Upvotes: 2

Related Questions