orderBy('sort_order') ->orderByDesc('rank') ->get(); return view('admin.departments.index', compact('departments')); } /** * 创建部门 */ public function store(Request $request): RedirectResponse { $data = $request->validate([ 'name' => 'required|string|max:50|unique:departments,name', 'rank' => 'required|integer|min:0|max:99', 'color' => 'required|string|max:10', 'sort_order' => 'required|integer|min:0', 'description' => 'nullable|string|max:255', ]); Department::create($data); return redirect()->route('admin.departments.index')->with('success', "部门【{$data['name']}】创建成功!"); } /** * 更新部门 */ public function update(Request $request, Department $department): RedirectResponse { $data = $request->validate([ 'name' => 'required|string|max:50|unique:departments,name,'.$department->id, 'rank' => 'required|integer|min:0|max:99', 'color' => 'required|string|max:10', 'sort_order' => 'required|integer|min:0', 'description' => 'nullable|string|max:255', ]); $department->update($data); return redirect()->route('admin.departments.index')->with('success', "部门【{$data['name']}】更新成功!"); } /** * 删除部门(级联删除职务) */ public function destroy(Department $department): RedirectResponse { // 检查是否有在职人员 $activeMemberCount = $department->positions() ->whereHas('activeUserPositions') ->count(); if ($activeMemberCount > 0) { return redirect()->route('admin.departments.index') ->with('error', "部门【{$department->name}】下尚有在职人员,请先撤销所有职务后再删除。"); } $department->delete(); return redirect()->route('admin.departments.index')->with('success', "部门【{$department->name}】已删除!"); } }