feat: implement company deletion functionality with confirmation dialog

This commit is contained in:
dkecskes
2025-11-03 19:37:04 +01:00
parent 3ff12fe57e
commit 1973ab6b7f
5 changed files with 274 additions and 2 deletions

View File

@@ -4,7 +4,10 @@ namespace App\Http\Controllers;
use App\Models\Company;
use App\Models\User;
use App\Models\Internship;
use App\Models\InternshipStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class CompanyController extends Controller
{
@@ -152,4 +155,67 @@ class CompanyController extends Controller
{
//
}
/**
* Delete a company, its contact person and all related data.
*/
public function delete(int $id)
{
$user = auth()->user();
// Admin kontrola
if ($user->role !== 'ADMIN') {
abort(403, 'Unauthorized');
}
$company = Company::find($id);
if (!$company) {
return response()->json([
'message' => 'No such company exists.'
], 400);
}
try {
DB::beginTransaction();
// 1. Získaj všetky internship IDs firmy
$internshipIds = Internship::where('company_id', $company->id)
->pluck('id')
->toArray();
// 2. Vymaž všetky internship statuses
if (!empty($internshipIds)) {
InternshipStatus::whereIn('internship_id', $internshipIds)->delete();
}
// 3. Vymaž všetky internships firmy
Internship::where('company_id', $company->id)->delete();
// 4. Získaj contact usera
$contactUser = User::find($company->contact);
// 5. Vymaž company
$company->delete();
// 6. Vymaž contact usera (EMPLOYER)
if ($contactUser && $contactUser->role === 'EMPLOYER') {
$contactUser->delete();
}
DB::commit();
return response()->json([
'message' => 'Company successfully deleted.'
], 200);
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
'message' => 'Error deleting company.',
'error' => $e->getMessage()
], 500);
}
}
}

View File

@@ -22,4 +22,20 @@ class Company extends Model
'contact',
'hiring'
];
/**
* Get the internships for the company.
*/
public function internships()
{
return $this->hasMany(Internship::class, 'company_id');
}
/**
* Get the contact person (user) for the company.
*/
public function contactPerson()
{
return $this->belongsTo(User::class, 'contact');
}
}

View File

@@ -54,4 +54,5 @@ Route::prefix('/companies')->middleware("auth:sanctum")->group(function () {
Route::get("/simple", [CompanyController::class, 'all_simple']);
Route::get("/{id}", [CompanyController::class, 'get']);
Route::post("/{id}", [CompanyController::class, 'update_all']);
Route::delete("/{id}", [CompanyController::class, 'delete']);
});