123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- namespace App\Http\Controllers\API;
- use App\Http\Controllers\Controller;
- use App\Http\Requests\API\Department\CreateOrUpdateRequest;
- use App\Http\Resources\API\DepartmentResource;
- use App\Models\Department;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Auth;
- class DepartmentController extends Controller
- {
- public function index(Request $request)
- {
- $sort=$request->input('sort','desc');
- $pageSize=$request->get('page_size') ?? 10;
- $department=Department::filter($request->all())->where("parent_id",0) ->orderBy('created_at',$sort)->with(['children'])->paginate($pageSize);
- return DepartmentResource::collection($department);
- }
- public function store(CreateOrUpdateRequest $request)
- {
- $department=new Department();
- $department->mergeFillable([
- 'company_id'
- ]);
- $department->fill([
- ...$request->all(),
- 'company_id' => Auth::user()->company_id,
- ]);
- $department->save();
- return $this->created();
- }
- public function show(string $id)
- {
- $department=Department::query()->findOrFail($id);
- return new DepartmentResource($department);
- }
- public function update(CreateOrUpdateRequest $request,string $id)
- {
- $department=Department::findOrFail($id);
- $department->fill($request->all());
- $department->save();
- return $this->noContent();
- }
- public function destroy(string $id)
- {
- $department = Department::findOrFail($id);
- if(!empty($department->children()->first())){
- throw new \Exception("Please remove the sub-level departments.");
- }
- $department->delete();
- return $this->noContent();
- }
- public function departmentUserIndex(){
- $companyId=Auth::user()->company_id;
- $department=Department::query()->where('company_id',$companyId)->with(['users'=>function($query){
- $query->select('id','name','department_id');
- }])->get(['id','name','parent_id']);
- return $this->success([
- 'data' => make_tree($department->toArray())
- ]);
- }
- }
|