简体   繁体   中英

How can I store request array without using foreach in Laravel?

I have an array in the post request as an example below:

$data = array(
    array('title'=>'1st title', 'desc'=>'desc'),
    array('title'=>'2nd title', 'desc'=>'desc'),
    array('title'=>'3rd title', 'desc'=>'desc'),
)

Is there a way in Laravel using Eloquent I can save above data without using foreach? Note that the array keys which I am getting in the request is not same as column names of the table.

I hope this would help you

$data = [
    ['title' => '1st title', 'desc' => 'desc'],
    ['title' => '2nd title', 'desc' => 'desc']
    .....
];

DB::table('users')->insert($data);

Put all the values you want to insert in to an array and then pass it to the insert function.

Source: https://laravel.com/docs/5.1/queries#inserts

尝试这个:

DB::table('table_name')->insert($data);

Using eloquent: just as mentioned by Sethu, but a few lines will be:

Model::insert($data); // eg: Posts::insert($your_request_array);

Just pass in the array directly here: above will return true on success.

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