88 lines
2.5 KiB
PHP
88 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Http\Request;
|
|
use App\Models\Category;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class DataCategoryController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$categories = Category::all();
|
|
return view('masterData.data-category', compact('categories'));
|
|
}
|
|
|
|
// Tambah kategori
|
|
public function store(Request $request)
|
|
{
|
|
$validator = Validator::make($request->all(), [
|
|
'name' => 'required|string|max:255',
|
|
]);
|
|
|
|
if ($validator->fails()) {
|
|
return redirect()->back()->withErrors($validator)->withInput();
|
|
}
|
|
|
|
try {
|
|
Category::create(['name' => $request->name]);
|
|
return redirect()->route('categories.index')->with('success', 'Category added successfully');
|
|
} catch (\Throwable $th) {
|
|
return redirect()->back()->with('error', 'An error occurred')->withInput();
|
|
}
|
|
}
|
|
|
|
|
|
// Edit kategori
|
|
public function edit($id)
|
|
{
|
|
$category = Category::find($id);
|
|
if (!$category) {
|
|
return redirect()->back()->with('error', 'Category not found');
|
|
}
|
|
return view('masterData.edit-category', compact('category'));
|
|
}
|
|
|
|
// Update kategori
|
|
public function update(Request $request, $id)
|
|
{
|
|
$validator = Validator::make($request->all(), [
|
|
'nama' => 'required|string|max:255',
|
|
]);
|
|
|
|
if ($validator->fails()) {
|
|
return redirect()->back()->withErrors($validator)->withInput();
|
|
}
|
|
|
|
$category = Category::find($id);
|
|
if (!$category) {
|
|
return redirect()->back()->with('error', 'Category not found');
|
|
}
|
|
|
|
$category->name = $request->nama;
|
|
|
|
try {
|
|
$category->save();
|
|
return redirect()->route('categories.index')->with('success', 'Category updated successfully');
|
|
} catch (\Throwable $th) {
|
|
return redirect()->back()->with('error', 'An error occurred')->withInput();
|
|
}
|
|
}
|
|
|
|
// Hapus kategori
|
|
public function destroy($id)
|
|
{
|
|
try {
|
|
$category = Category::findOrFail($id);
|
|
$category->delete();
|
|
|
|
return redirect()->back()->with('success', 'Category deleted successfully');
|
|
} catch (\Exception $e) {
|
|
Log::error('Failed to delete category: ' . $e->getMessage());
|
|
return redirect()->back()->with('error', 'Failed to delete category');
|
|
}
|
|
}
|
|
}
|