Laravel项目中如何将多选下拉框的多个院校值存入数据库对应字段
步骤1:修改前端多选选择器配置
你当前的select标签name属性不符合多选传值要求,浏览器默认只会传递最后一个选中值,需要把name="university"改为name="university[]",修改后代码如下:
<select class="selectpicker" multiple data-live-search="true" name="university[]"> @foreach($districts as $row) <option value="{{$row->name}}" {{ isset($sellerInfo) && in_array($row->name, $sellerInfo->university) ? 'selected' : '' }}> {{$row->name}} </option> @endforeach </select>
上面代码额外加了编辑场景下的已选值回显逻辑,不需要可以删掉。
方案A:JSON序列化存储(改动最小,适合轻量场景)
如果你不需要单独按院校筛选查询学生数据,用这个方案最快:
修改数据库字段类型
新建迁移文件修改university字段:
执行命令php artisan make:migration modify_university_column_for_seller_infos
迁移文件内容如下:use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up() { Schema::table('seller_infos', function (Blueprint $table) { $table->json('university')->nullable()->change(); }); } public function down() { Schema::table('seller_infos', function (Blueprint $table) { $table->string('university')->nullable()->change(); }); } };执行迁移命令
php artisan migrate生效。修改模型配置
在Seller_info模型中添加类型转换配置,自动处理数组和JSON的互转:protected $casts = [ 'university' => 'array' ];控制器逻辑无需修改,直接提交即可自动序列化多个院校值存储,读取时也会自动转为数组使用。
方案B:关联表存储(符合数据库范式,适合复杂查询场景)
如果你后续需要按院校统计学生、筛选查询学生,推荐用一对多关联表设计:
新建关联表
执行命令php artisan make:migration create_student_universities_table
迁移文件内容如下:use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up() { Schema::create('student_universities', function (Blueprint $table) { $table->id(); $table->foreignId('seller_info_id')->constrained()->onDelete('cascade'); $table->string('university_name'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('student_universities'); } };执行迁移命令
php artisan migrate生效。新建关联模型
执行命令php artisan make:model StudentUniversity,配置$fillable:protected $fillable = ['seller_info_id', 'university_name'];配置Seller_info模型关联
在Seller_info模型中添加关联方法:public function universities() { return $this->hasMany(StudentUniversity::class); }同时可以删掉原来的
university字段的$fillable配置和数据库字段。修改控制器store方法
先创建学生记录,再批量插入关联院校:public function store(Request $request) { $student = Seller_info::create($request->only([ 'name', 'email', 'passport', 'phone_number','address','dateofbirth','ielts', 'openingcharge','serviceCharge','applydate','visaStatus','country' ])); // 批量插入关联院校 $universities = collect($request->university)->map(fn($uni) => ['university_name' => $uni]); $student->universities()->createMany($universities); return back(); }读取数据时通过
$student->universities即可获取所有关联院校列表。
可选补充:请求校验
建议在store方法开头添加校验规则,避免非法值提交:
$request->validate([ 'university' => 'required|array', 'university.*' => 'required|string' ]);
内容的提问来源于stack exchange,提问作者Oni Sama

