CreateOrUpdateRequest.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Http\Requests\API\RequirementGroup;
  3. use App\Http\Requests\RuleHelper;
  4. use Illuminate\Foundation\Http\FormRequest;
  5. use Illuminate\Validation\Rule;
  6. /**
  7. */
  8. class CreateOrUpdateRequest extends FormRequest
  9. {
  10. use RuleHelper;
  11. /**
  12. * Determine if the user is authorized to make this request.
  13. */
  14. public function authorize(): bool
  15. {
  16. return true;
  17. }
  18. /**
  19. * Get the validation rules that apply to the request.
  20. *
  21. * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
  22. */
  23. public function rules(): array
  24. {
  25. return [
  26. 'asset_id' => [
  27. 'nullable',
  28. Rule::exists('assets', 'id')->where($this->userCompanyWhere()),
  29. ],
  30. 'name' => 'required|max:255',
  31. 'abbr_name' => 'required|max:30',
  32. 'parent_id' => [
  33. $this->parentIdExistsRule(),
  34. ]
  35. ];
  36. }
  37. protected function parentIdExistsRule()
  38. {
  39. // 如果 parent_id 不为 0,返回 exists 规则
  40. if ($this->input('parent_id') != 0) {
  41. return Rule::exists('requirement_groups', 'id')->where($this->userCompanyWhere())->where('asset_id', $this->input('asset_id'));
  42. }
  43. // 如果 parent_id 为 0,返回空数组以跳过 exists 验证
  44. return [];
  45. }
  46. }