TIFNJK_E41222887/app/Http/Controllers/Admin/DepartmentController.php

68 lines
1.8 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Department;
use Illuminate\Http\Request;
use Inertia\Inertia;
class DepartmentController extends Controller
{
public function index()
{
return Inertia::render('admin/departments/index', [
'departments' => Department::withCount('employees')->latest()->get(),
]);
}
public function create()
{
return Inertia::render('admin/departments/create');
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255|unique:departments,name',
'description' => 'nullable|string',
]);
Department::create($validated);
return redirect()->to('/admin/departments')
->with('success', 'Departemen berhasil ditambahkan.');
}
public function edit(Department $department)
{
return Inertia::render('admin/departments/edit', [
'department' => $department
]);
}
public function update(Request $request, Department $department)
{
$validated = $request->validate([
'name' => 'required|string|max:255|unique:departments,name,' . $department->id,
'description' => 'nullable|string',
]);
$department->update($validated);
return redirect()->to('/admin/departments')
->with('success', 'Departemen berhasil diperbarui.');
}
public function destroy(Department $department)
{
// Cek jika departemen masih punya karyawan
if ($department->employees()->count() > 0) {
return back()->with('error', 'Gagal hapus! Departemen ini masih memiliki karyawan.');
}
$department->delete();
return back()->with('success', 'Departemen berhasil dihapus.');
}
}