admin and mod categories management

This commit is contained in:
Doar Mihai
2026-02-21 14:57:38 +02:00
parent 2c74b38ffc
commit 0f17570476
7 changed files with 552 additions and 3 deletions
@@ -0,0 +1,104 @@
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class CategoryManagementController extends Controller
{
/**
* Display a listing of categories.
*/
public function index(Request $request)
{
$query = Category::withCount('products');
// Search
if ($request->filled('search')) {
$search = $request->search;
$query->where(function ($q) use ($search) {
$q->where('name', 'like', "%{$search}%")
->orWhere('description', 'like', "%{$search}%");
});
}
$categories = $query->latest()->paginate(20);
return view('categories.index', compact('categories'));
}
/**
* Show the form for creating a new category.
*/
public function create()
{
return view('categories.create');
}
/**
* Store a newly created category.
*/
public function store(Request $request)
{
$validated = $request->validate([
'name' => ['required', 'string', 'max:255', 'unique:categories,name'],
'description' => ['nullable', 'string', 'max:1000'],
]);
// Generate unique slug
$validated['slug'] = Category::generateUniqueSlug($validated['name']);
Category::create($validated);
return redirect()->route('categories.index')
->with('success', 'Category created successfully.');
}
/**
* Show the form for editing a category.
*/
public function edit(Category $category)
{
return view('categories.edit', compact('category'));
}
/**
* Update the specified category.
*/
public function update(Request $request, Category $category)
{
$validated = $request->validate([
'name' => ['required', 'string', 'max:255', Rule::unique('categories')->ignore($category->id)],
'description' => ['nullable', 'string', 'max:1000'],
]);
// Regenerate slug if name changed
if ($category->name !== $validated['name']) {
$validated['slug'] = Category::generateUniqueSlug($validated['name'], $category->id);
}
$category->update($validated);
return redirect()->route('categories.index')
->with('success', 'Category updated successfully.');
}
/**
* Remove the specified category.
*/
public function destroy(Category $category)
{
// Check if category has products
if ($category->products()->count() > 0) {
return redirect()->route('categories.index')
->with('error', "Cannot delete category '{$category->name}' because it has {$category->products()->count()} products. Please reassign or delete those products first.");
}
$category->delete();
return redirect()->route('categories.index')
->with('success', 'Category deleted successfully.');
}
}