JezK
Edit File: CategoryService.php
<?php namespace App\Services; use App\Models\Category; use Illuminate\Database\Eloquent\Collection; class CategoryService { public function __construct( protected SlugService $slugService ) {} public function getAll(): Collection { return Category::with('children') ->withCount('articles') ->roots() ->ordered() ->get(); } public function getAllFlat(): Collection { return Category::ordered()->get(); } public function getActive(): Collection { return Category::active()->withCount('articles')->ordered()->get(); } public function findById(int $id): ?Category { return Category::with(['parent', 'children'])->withCount('articles')->find($id); } public function findBySlug(string $slug): ?Category { return Category::with('children')->active()->where('slug', $slug)->first(); } public function create(array $data): Category { $data['slug'] = $this->slugService->generate(Category::class, $data['name']); return Category::create($data); } public function update(Category $category, array $data): Category { if (isset($data['name']) && $data['name'] !== $category->name) { $data['slug'] = $this->slugService->generate(Category::class, $data['name'], $category->id); } $category->update($data); return $category->fresh(); } public function delete(Category $category): bool { // Move children to parent before deleting if ($category->children()->count() > 0) { $category->children()->update(['parent_id' => $category->parent_id]); } return $category->delete(); } }