简体   繁体   中英

Insert multiple rows in laravel with json payload

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')
                )
            ));
        }

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM