1

I have an angular post request going to a laravel controller function inserting into a db. The payload looks like this:

[
{"id":1,"utid":"ABC","name":"Introduction","docId":1,"position":1},
{"id":2,"utid":"DEF","name":"Chapter One","docId":1,"position":2},
{"utid":"GHI","name":"asd","docId":1,"position":3}
]

How do I extract the inputs and assign them correctly to the database command. I imagine something with foreach but I don't know the synthax. Can anyone help me?

foreach($topics as $topic => $insert )
        {
            DB::table('topics')->insert(array(
                array(
                    'utid' => Input::json('utid'),
                    'name' => Input::json('name'),
                    'docId' => Input::json('docId'),
                    'position' => Input::json('position')
                )
            ));
        }

1 Answer 1

1

Try json_decode first:

$json = '[
    {"id":1,"utid":"ABC","name":"Introduction","docId":1,"position":1},
    {"id":2,"utid":"DEF","name":"Chapter One","docId":1,"position":2},
    {"utid":"GHI","name":"asd","docId":1,"position":3}
]';

$data = json_decode($json);

Then you could use Post::create($data); to create new entries.

To do that you would also need to setup your model to allow mass assignment for these fields:

protected $fillable = ['utid', 'name', 'Introduction'];

You can find more about it in the official Laravel documentation here.

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

2 Comments

When I do this, I get an error saying SQLSTATE[HY000]: General error: 1364 Field 'utid' doesn't have a default value (SQL: insert into 'topics' () values ())
Well, that means that utid is NULL or empty and probably need to be set before you try to create the model.

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.