温馨提示:本文翻译自stackoverflow.com,查看原文请点击:php - Laravel

php - Laravel

发布于 2020-03-27 15:38:49

我正在使用开发一个Web应用程序Laravel-5.8

我有这个Laravel模型:

class Employee extends Model
{
    protected $table = 'employees';
    protected $fillable = [
              'employee_code',
              'supervisor_id',
              'first_name',
              'emp_image',
              'last_name',
          ];

    public function supervisor()
    {
        return $this->belongsTo('App\Models\Employee','supervisor_id');
    }
}

控制者

public function index()
{
    $employees = Employee::all();
    return view('employees.index')->with('employees', $employees);
}


public function create()
{
    $supervisors = Employee::all();
    return view('employees.create')->with('supervisors', $supervisors);
}

public function store(StoreEmployeeRequest $request)
{
    try {
            $designation = Employee::create([
                'employee_code'      => $request->employee_code,
                'supervisor_id'        => $request->supervisor_id,
                'first_name'           => $request->first_name,
                'last_name'           => $request->last_name,
            ]);
            Session::flash('success', 'Employee is created successfully');
            return redirect()->route('employees.index');
    } catch (Exception $exception) {
            Session::flash('danger', 'Employee creation failed!');
            return redirect()->route('employees.index');
    }
}

create.blade

<div class="form-group">
   <label>Employee Code<span style="color:red;">*</span></label>
   <input  type="text" name="employee_code" placeholder="Enter employee code here" class="form-control" value="{{old('employee_code')}}">
</div>

<select class="form-control select2bs4" data-placeholder="Choose Supervisor" tabindex="1" name="grade_level_id" style="width: 100%;">>
    <option value="">Select Supervisor</option>
     @if($supervisors->count() > 0)
        @foreach($supervisors as $supervisor)
           <option value="{{$supervisor->id}}">{{$supervisor->employee_code}}</option>
        @endforeach
     @endif
</select>

每个employee都有他或supervisor主管来自员工表- supervisor_id选择主管下拉列表后,它将加载employee_code,然后将员工数据保存在数据库中。

我已经尝试了上面的代码,但下拉列表中没有任何内容。如何重新编写控制器,视图和模型以实现此目的?

查看更多

查看更多

提问者
mikefolu
被浏览
91
Marian Rencsik 2020-01-31 16:34

您已经在employee.create视图函数中发送了$ supervisor,您应该发送$ supervisor。

public function create()
{
    $supervisors = Employee::all();
    return view('employees.create')->with('supervisors', $supervisor);
}

并且您应该将选择名称更改为supervisor_id,而不是grade_level_id。

<select class="form-control select2bs4" data-placeholder="Choose Supervisor" tabindex="1" name="supervisor_id" style="width: 100%;">>
    <option value="">Select Supervisor</option>
     @if($supervisors->count() > 0)
        @foreach($supervisors as $supervisor)
           <option value="{{$supervisor->id}}">{{$supervisor->employee_code}}</option>
        @endforeach
     @endif
</select>