orderBy('key') ->get(); return response()->json([ 'success' => true, 'data' => [ 'configs' => $configs, ], ]); } public function store(Request $request): JsonResponse { $data = $request->validate([ 'key' => ['required', 'string', 'max:255', 'unique:configs,key'], 'value' => ['nullable', 'string'], 'description' => ['nullable', 'string', 'max:255'], ]); $config = Config::query()->create([ 'key' => $data['key'], 'value' => $this->decodeValue($data['value'] ?? null), 'description' => $data['description'] ?? null, ]); return response()->json([ 'success' => true, 'data' => [ 'config' => $config, ], ]); } public function update(Request $request, Config $config): JsonResponse { $data = $request->validate([ 'key' => [ 'required', 'string', 'max:255', Rule::unique('configs', 'key')->ignore($config->id), ], 'value' => ['nullable', 'string'], 'description' => ['nullable', 'string', 'max:255'], ]); $config->update([ 'key' => $data['key'], 'value' => $this->decodeValue($data['value'] ?? null), 'description' => $data['description'] ?? null, ]); return response()->json([ 'success' => true, 'data' => [ 'config' => $config->refresh(), ], ]); } public function destroy(Config $config): JsonResponse { $config->delete(); return response()->json([ 'success' => true, ]); } private function decodeValue(?string $raw): mixed { if ($raw === null) { return null; } $trimmed = trim($raw); if ($trimmed === '') { return null; } $decoded = json_decode($trimmed, true); if (json_last_error() !== JSON_ERROR_NONE) { throw ValidationException::withMessages([ 'value' => 'value 必须是合法 JSON', ]); } return $decoded; } }