I'm kinda new to Laravel, I ran into some problems with inserting multiple select to multiple columns in the database.
Here my view I'm using select picker for multiple select
<select multiple="multiple" name=language[] id="language[]" class="selectpicker" data-selected-text-format="count">
<option name="En">English</option>
<option name="It">Italian</option>
<option name="Ar">Arabic</option>
<option name="Jp">Japanese</option>
</select>
The languages table:
+----+---------+---------+--------+--------+
| id | English | Italian | Arabic |Japanese|
+----+---------+---------+--------+--------+
| 1 | | | | |
| 2 | | | | |
| 3 | | | | |
+----+---------+---------+--------+--------+
How can I insert data to each column in the controller?
Here what I'm trying to do!
+----+---------+---------+--------+--------+
| id | English | Italian | Arabic |Japanese|
+----+---------+---------+--------+--------+
| 1 | En | | Ar | Jp |
| 2 | | It | | |
| 3 | En | | | Jp |
+----+---------+---------+--------+--------+
First, make sure the tables id
column is set to auto increment
. and other columns as nullable
.
$languages = request('languages');
DB::table('table_name')->insert([
'English' => in_array('En', $languages) ? 'En' : null,
'Italian' => in_array('It', $languages) ? 'It' : null,
'Arabic' => in_array('Ar', $languages) ? 'Ar' : null,
'Japanese' => in_array('Jp', $languages) ? 'Jp' : null,
]);
You'll receive an array language
in your controller so you can check if the language exists add it to the DB :
$en = $it = $ar = $jp = null;
if(in_array('En', $language))
$en = 'En';
if(in_array('It', $language))
$it = 'It';
if(in_array('Ar', $language))
$ar = 'Ar';
if(in_array('Jp', $language))
$jp = 'Jp';
ModelName::insert(['English' => $en, 'Italian' => $it, 'Arabic' => $ar, 'Japanes' => $jp]);
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.