From 1f3eb8576a5273a715d98352c4a1b7b5183c3e70 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Thu, 14 Mar 2024 15:39:23 +0700 Subject: [PATCH] update delete relative company --- app/Http/Controllers/CompanyController.php | 39 ++++++++++++++-------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index 3a0cecb..b828469 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -2,9 +2,9 @@ namespace App\Http\Controllers; -use App\Models\Company; -use App\Models\MenuCompany; +use App\Models\{User, RoleMenu, Role, ProductTransaction, MenuCompany, Company}; use Illuminate\Http\Request; +use Illuminate\Support\Facades\DB; class CompanyController extends Controller { @@ -66,8 +66,6 @@ class CompanyController extends Controller return response()->json(['status' => 'failed', 'message' => 'data Company not found!', 'code' => 400], 400); die(); } - - if ($result) { return response()->json(['status' => 'success', 'message' => 'data Company successfully updated!', 'code' => 200], 200); } else { @@ -77,24 +75,37 @@ class CompanyController extends Controller public function delete($id) { - $data = Company::find($id); - + DB::beginTransaction(); + $data = Company::find((int)$id); if ($data) { - MenuCompany::where('company_id',$id)->delete(); - $delete = $data->delete(); + $this->deleteRelative((int)$data['id']); + if ($data->delete()) { + DB::commit(); + return response()->json(['status' => 'success', 'message' => 'Data Company successfully deleted!', 'code' => 200], 200); + } else { + DB::rollBack(); + return response()->json(['status' => 'failed', 'message' => 'Data Company failed deleted!', 'code' => 400], 400); + } } else { - return response()->json(['status' => 'failed', 'message' => 'data Company not found!', 'code' => 400], 400); + DB::rollBack(); + return response()->json(['status' => 'failed', 'message' => 'Data Company not found!', 'code' => 400], 400); die(); } + } - - if ($delete) { - return response()->json(['status' => 'success', 'message' => 'data Company successfully deleted!', 'code' => 200], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'data Company failed deleted!', 'code' => 400], 400); + private function deleteRelative($company_id) + { + MenuCompany::where('company_id', $company_id)->delete(); + User::where('company_id', $company_id)->delete(); + $role = Role::where('company_id', $company_id)->first(); + if ($role) { + RoleMenu::where('role_id', $role->id)->delete(); + $role->delete(); } + ProductTransaction::where('company_id', $company_id)->delete(); } + public function search(Request $request) { $payload = $request->all();