DepartmentController.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Http\Controllers\API;
  3. use App\Http\Controllers\Controller;
  4. use App\Http\Requests\API\Department\CreateOrUpdateRequest;
  5. use App\Http\Resources\API\DepartmentResource;
  6. use App\Models\Department;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\Auth;
  9. class DepartmentController extends Controller
  10. {
  11. public function index(Request $request)
  12. {
  13. $pageSize=$request->get('page_size') ?? 10;
  14. $department=Department::filter($request->all())->where("parent_id",0)->with(['children'])->paginate($pageSize);
  15. return DepartmentResource::collection($department);
  16. }
  17. public function store(CreateOrUpdateRequest $request)
  18. {
  19. $department=new Department();
  20. $department->mergeFillable([
  21. 'company_id'
  22. ]);
  23. $department->fill([
  24. ...$request->all(),
  25. 'company_id' => Auth::user()->company_id,
  26. ]);
  27. $department->save();
  28. return $this->created();
  29. }
  30. public function show(string $id)
  31. {
  32. $department=Department::query()->findOrFail($id);
  33. return new DepartmentResource($department);
  34. }
  35. public function update(CreateOrUpdateRequest $request,string $id)
  36. {
  37. $department=Department::findOrFail($id);
  38. $department->fill($request->all());
  39. $department->save();
  40. return $this->noContent();
  41. }
  42. public function destroy(string $id)
  43. {
  44. $department = Department::findOrFail($id);
  45. if(!empty($department->children()->first())){
  46. throw new \Exception("Please remove the sub-level departments.");
  47. }
  48. $department->delete();
  49. return $this->noContent();
  50. }
  51. public function departmentUserIndex(){
  52. $companyId=Auth::user()->company_id;
  53. $department=Department::query()->where('company_id',$companyId)->with(['users'=>function($query){
  54. $query->select('id','name','department_id');
  55. }])->get(['id','name','parent_id']);
  56. return $this->success([
  57. 'data' => make_tree($department->toArray())
  58. ]);
  59. }
  60. }