DepartmentController.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. $department=Department::filter($request->all())->where("parent_id",0)->with(['children'])->simplePaginate();
  14. return DepartmentResource::collection($department);
  15. }
  16. public function store(CreateOrUpdateRequest $request)
  17. {
  18. $department=new Department();
  19. $department->mergeFillable([
  20. 'company_id'
  21. ]);
  22. $department->fill([
  23. ...$request->all(),
  24. 'company_id' => Auth::user()->company_id,
  25. ]);
  26. $department->save();
  27. return $this->created();
  28. }
  29. public function show(string $id)
  30. {
  31. $department=Department::query()->findOrFail($id);
  32. return new DepartmentResource($department);
  33. }
  34. public function update(CreateOrUpdateRequest $request,string $id)
  35. {
  36. $department=Department::findOrFail($id);
  37. $department->fill($request->all());
  38. $department->save();
  39. return $this->noContent();
  40. }
  41. public function destroy(string $id)
  42. {
  43. $department = Department::findOrFail($id);
  44. if(!empty($department->children()->first())){
  45. throw new \Exception("Please remove the sub-level departments.");
  46. }
  47. $department->delete();
  48. return $this->noContent();
  49. }
  50. }