'sometimes|integer', 'entry_date' => 'sometimes|date_format:Y-m-d', 'user_information_history' => 'sometimes|string|max:255', ]; } /** * バリデーションエラーメッセージ */ public function messages(): array { return [ 'user_id.integer' => 'E03: user_id は整数で指定してください。', 'entry_date.date_format' => 'E04: entry_date の形式が不正です。YYYY-MM-DD形式で指定してください。', 'user_information_history.string' => 'E05: user_information_history は文字列で指定してください。', 'user_information_history.max' => 'E05: user_information_history が255文字を超えています。', ]; } /** * 追加バリデーション */ public function withValidator(Validator $validator) { $validator->after(function ($validator) { // 少なくとも1つの更新項目が必要 $updateFields = array_filter( $this->only(['user_id', 'entry_date', 'user_information_history']), function ($value) { return $value !== null; } ); if (empty($updateFields)) { $validator->errors()->add('_general', 'E06: 更新項目が1つも指定されていません。'); } // user_idの存在チェック if (!$validator->errors()->has('user_id') && $this->has('user_id') && $this->user_id !== null) { if (!User::where('user_id', $this->user_id)->exists()) { $validator->errors()->add('user_id', 'E03: 指定された user_id が userテーブルに存在しません。'); } } }); } /** * バリデーション失敗時の処理 */ protected function failedValidation(Validator $validator) { $errors = $validator->errors()->first(); // エラーコード抽出 preg_match('/^(E\d{2}):/', $errors, $matches); $errorCode = $matches[1] ?? 'E99'; $message = preg_replace('/^E\d{2}: /', '', $errors); throw new HttpResponseException( response()->json([ 'error' => [ 'code' => $errorCode, 'message' => $message ] ], 400) ); } }