Laravel中如何向多列插入多值?新手技术求助
Hey there! Let's work through this step by step. First, I spotted a small but crucial issue in your view that we need to fix first—your <option> tags don't have value attributes right now. Without them, when you submit the form, it'll send the visible text (like "English") instead of the code "En" you want stored in the database. Let's update that:
<select multiple="multiple" name="language[]" id="language" class="selectpicker" data-selected-text-format="count"> <option value="En">English</option> <option value="It">Italian</option> <option value="Ar">Arabic</option> <option value="Jp">Japanese</option> </select>
(Note: You don't need [] in the id attribute—only the name needs it to tell Laravel to treat the input as an array.)
Now, let's handle the insertion in your controller. The goal is to map each selected language code to its corresponding column in the languages table, leaving unselected columns empty. Here's how to do it:
Controller Code
Assuming you have an Eloquent model named Language (linked to your languages table), here's the store method:
use App\Models\Language; use Illuminate\Http\Request; public function store(Request $request) { // Get selected languages, default to empty array if none are chosen $selectedLanguages = $request->input('language', []); // Initialize an array with all columns set to empty strings $languageData = [ 'English' => '', 'Italian' => '', 'Arabic' => '', 'Japanese' => '', ]; // Map each selected code to the correct database column foreach ($selectedLanguages as $code) { match ($code) { 'En' => $languageData['English'] = 'En', 'It' => $languageData['Italian'] = 'It', 'Ar' => $languageData['Arabic'] = 'Ar', 'Jp' => $languageData['Japanese'] = 'Jp', }; } // Insert the data into the database Language::create($languageData); // Optional: Redirect back with a success message return redirect()->back()->with('success', 'Language preferences saved!'); }
Important Notes:
- Mass Assignment: Make sure your
Languagemodel has the columns listed in the$fillableproperty to allow Laravel to insert data viacreate():// In app/Models/Language.php protected $fillable = ['English', 'Italian', 'Arabic', 'Japanese']; - Fallback for No Selection: Using
$request->input('language', [])ensures we get an empty array instead ofnullif no languages are selected, which prevents errors in the loop. - Alternative with DB Facade: If you prefer not to use Eloquent, you can replace
Language::create($languageData)with:DB::table('languages')->insert($languageData);
This will produce exactly the database output you're looking for—selected language codes in their respective columns, and empty values for unselected ones.
内容的提问来源于stack exchange,提问作者Sul Alo

