You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8表单下拉选部门数据报$depts未定义如何解决

错误原因及修复方案

1. 控制器未给表单视图传递$depts变量

如果加载表单的路由指向的是create方法,现有create方法仅查询了部门数据,没有将变量传递给视图就直接结束,视图自然读取不到$depts。如果路由指向的是index方法,还存在字段名写错的问题。
修改控制器代码:

// 如果是create方法加载表单
public function create()
{
    // 注意Department表的字段是dept_name,不是你之前写的department_name,pluck第二个参数传id作为选项值
    $depts = DB::table('departments')->pluck('dept_name', 'id');
    return view('strategic_plan.people_form', compact('depts'));
}

// 如果是index方法加载表单,对应修改index逻辑
public function index()
{
    $depts = DB::table('departments')->pluck('dept_name', 'id');
    return view('strategic_plan.people_form', compact('depts'));
}

另外要检查你的表单访问路由,不要用直接返回视图的闭包路由,必须绑定到控制器方法才能处理变量传递:

// 路由示例(web.php中)
Route::get('/person/create', [\App\Http\Controllers\PeopleController::class, 'create']);

2. 下拉框代码写法错误

Form::select本身支持直接接收数组渲染选项,不需要套@foreach,你现在的写法就算变量传对了,也会生成N个下拉框而不是一个带N个选项的下拉框。把表单中部门选择部分的代码全部替换为:

{{Form::label('Department', 'Department')}}
{{Form::select('department', $depts, null, ['class'=>'form-control','placeholder' => 'Select Department'])}}

3. 存储逻辑存在两处致命错误

现有store方法即使前端参数传对也会报错,修改为:

public function store(Request $request)
{
    $this->validate($request,[
        'names'=>'required',
        'department'=>'required',
        'level' =>'required'    
    ]);

    $persons = new People;
    // 字段名要和你Persons表的实际字段对应
    $persons->Persons_names = $request->input('names');
    $persons->Dept_name = $request->input('department');
    $persons->Position_held = $request->input('level');
    // 原代码变量名写错,是$persons不是$dept
    $persons->save();

    return redirect('/people')->with('message','人员添加成功');
}

内容的提问来源于stack exchange,提问作者ANTHONY MWANGI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:36:05