From e125ac34d7af9c0289f1a19b9bd773f242cc8fc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrg=20Hallenbarter?= Date: Wed, 13 May 2026 14:25:32 +0200 Subject: [PATCH] fix category duplicates: validate unique name on create and rename, return proper 409 error instead of SQL 500 --- app/Controllers/Api/V1/CategoryController.php | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/app/Controllers/Api/V1/CategoryController.php b/app/Controllers/Api/V1/CategoryController.php index 5f7e353..9da6885 100644 --- a/app/Controllers/Api/V1/CategoryController.php +++ b/app/Controllers/Api/V1/CategoryController.php @@ -44,6 +44,16 @@ class CategoryController extends BaseController return; } + // Check for duplicate name per user + $existing = $this->categoryModel + ->where('user_id', $userId) + ->where('name', $json['name']) + ->first(); + + if ($existing) { + return $this->errorResponse('A category with this name already exists.', 409); + } + $data = [ 'id' => $this->generateUuid(), 'user_id' => $userId, @@ -88,6 +98,20 @@ class CategoryController extends BaseController } $json = $this->request->getJSON(true); + + // Check for duplicate name on rename (excluding current category) + if (!empty($json['name']) && strtolower($json['name']) !== strtolower($category['name'])) { + $existing = $this->categoryModel + ->where('user_id', $userId) + ->where('name', $json['name']) + ->where('id !=', $id) + ->first(); + + if ($existing) { + return $this->errorResponse('A category with this name already exists.', 409); + } + } + $allowedFields = ['name', 'color', 'favorite']; $updateData = array_intersect_key($json, array_flip($allowedFields));