DepartmentController.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. $sort=$request->input('sort','desc');
  14. $pageSize=$request->get('page_size') ?? 10;
  15. $department=Department::filter($request->all())->where("parent_id",0) ->orderBy('created_at',$sort)->with(['children'])->paginate($pageSize);
  16. return DepartmentResource::collection($department);
  17. }
  18. public function store(CreateOrUpdateRequest $request)
  19. {
  20. $department=new Department();
  21. $department->mergeFillable([
  22. 'company_id'
  23. ]);
  24. $department->fill([
  25. ...$request->all(),
  26. 'company_id' => Auth::user()->company_id,
  27. ]);
  28. $department->save();
  29. return $this->created();
  30. }
  31. public function show(string $id)
  32. {
  33. $department=Department::query()->findOrFail($id);
  34. return new DepartmentResource($department);
  35. }
  36. public function update(CreateOrUpdateRequest $request,string $id)
  37. {
  38. $department=Department::findOrFail($id);
  39. $department->fill($request->all());
  40. $department->save();
  41. return $this->noContent();
  42. }
  43. public function destroy(string $id)
  44. {
  45. $department = Department::findOrFail($id);
  46. if(!empty($department->children()->first())){
  47. throw new \Exception("Please remove the sub-level departments.");
  48. }
  49. $department->delete();
  50. return $this->noContent();
  51. }
  52. public function departmentUserIndex(){
  53. $companyId=Auth::user()->company_id;
  54. $department=Department::query()->where('company_id',$companyId)->with(['users'=>function($query){
  55. $query->select('id','name','department_id');
  56. }])->get(['id','name','parent_id']);
  57. return $this->success([
  58. 'data' => make_tree($department->toArray())
  59. ]);
  60. }
  61. }