I am Developing a Web Application with Laravel-5.8
.
I have this Laravel model:
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');
}
}
Controller
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>
Each employee
have his or supervisor
. The supervisor is derived from employee table - supervisor_id
.
When the supervisor dropdownlist is selected it loads employee_code
and then save the employee data in the database.
I have tried the codes above but nothing is in the dropdownlist. How do I re-write my controller, view and model to achieve this?
You have sent the $supervisor in the employees.create view function, you should send $supervisors.
public function create()
{
$supervisors = Employee::all();
return view('employees.create')->with('supervisors', $supervisor);
}
and you should change the select name to supervisor_id instead of 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>