2

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?

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

SQLSTATE[HY000]: General error: 1364 Field 'paramJson' doesn't have a default value.
0

i change

Poll model:

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

it works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.