简体   繁体   中英

Laravel: How to insert multi select2 dropdown selected data to mysql database?

I am trying to insert data into database. But i don't know how to insert multi select data into the mysql database.

You have to to iterate through the multi select array then save one by one.

foreach ($_POST['your_key'] as $selectedOption) {
   // save $selectedOption to database
}

I am not quite sure what you mean by multi-select

But I am going to tell you how to inset more than one row in a shot in database in Laravel.

First, You make an associative array of data you want to insert, which will contain column name as key and value as the value you want to insert. Lets say you have a table named users in which you want to insert 4 new rows with different names you got from your form:

$data = [
  ['name'=>'xxx'],
  ['name'=>'yyy'],
  ['name'=>'zzz'],
  ['name'=>'qqq']
];

Then you use model for that table(in our case: users) which will be most likely: User to insert data in one shot:

User::insert($data);

Let's say you've got a table that have 2 columns :

CREATE TABLE table(
    id int not null primary key auto_increment,
    selectValue /*Whatever*/
)

And you've got a select named "MultipleValues[]" ( <select name='MultipleValues[]' multiple='multiple'/> ) so at your controller :

public function update(Request $request)
{
    $insertData = [];
    $multipleValues = $request->get('MultipleValues');
    foreach($multipleValues as $value)
    {
        $insertData['selectValue'] = $value;
    }
    DB::table('table')->insert($insertData);
}

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