join('cadastro_setor_tipo', 'cadastro_setor_tipo.id', 'cadastro_setor.tipo_id') ->leftJoin('cadastro_servico', 'cadastro_servico.id', 'cadastro_setor.servico_id') ->select( 'cadastro_setor_tipo.nome AS tipo', 'cadastro_servico.nome AS servico', 'cadastro_setor.id', 'cadastro_setor.nome', ) ->whereNull('cadastro_setor.deleted_at'); return datatables()->of($setores)->skipTotalRecords()->make(true); } public function index() { $this->auth(__FUNCTION__); $setores = $this->get(Setor::class)->orderBy('nome')->get(); return response()->json($setores, Response::HTTP_OK); } public function create() { $this->auth(__FUNCTION__); return response()->json( [ 'form' => $this->getFormData(), ], Response::HTTP_OK ); } public function store(SetorRequest $request) { $this->auth(__FUNCTION__); $setor = Setor::create($this->getParams($request))->fresh(); return response()->json($setor, Response::HTTP_CREATED); } public function show(int $id) { $this->auth(__FUNCTION__); return response()->json($this->get(Setor::class, $id), Response::HTTP_OK); } public function edit($id) { $this->auth(__FUNCTION__); $setor = Setor::findOrFail($id); return response()->json( [ 'form' => $this->getFormData(), 'model' => [ 'tipo_id' => $setor->tipo_id, 'servico_id' => $setor->servico_id, 'nome' => $setor->nome, ], ], Response::HTTP_OK ); } private function getFormData() { return [ 'tipos' => SetorTipo::orderBy('nome')->get()->map(fn ($tipo) => [ 'id' => $tipo->id, 'nome' => $tipo->nome, ]), 'servicos' => Servico::orderBy('nome')->get()->map(fn ($servico) => [ 'id' => $servico->id, 'nome' => $servico->nome, ]), ]; } public function update(SetorRequest $request, int $id) { $this->auth(__FUNCTION__); $setor = tap(Setor::findOrFail($id))->update($this->getParams($request)); return response()->json($setor->fresh(), Response::HTTP_OK); } private function getParams($request) { return [ 'tipo_id' => $request->tipo_id, 'servico_id' => $request->servico_id, 'nome' => mb_strtoupper($request->nome), ]; } public function destroy($id) { $this->auth(__FUNCTION__); Setor::findOrFail($id)->delete(); return response()->json(null, Response::HTTP_NO_CONTENT); } }