CreateOrUpdateRequest.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace App\Http\Requests\API\Asset;
  3. use App\Http\Requests\RuleHelper;
  4. use App\Models\Enums\AssetStatus;
  5. use App\Models\User;
  6. use Illuminate\Foundation\Http\FormRequest;
  7. use Illuminate\Support\Facades\Auth;
  8. use Illuminate\Validation\Rule;
  9. use Illuminate\Validation\Rules\Enum;
  10. class CreateOrUpdateRequest extends FormRequest
  11. {
  12. use RuleHelper;
  13. /**
  14. * Determine if the user is authorized to make this request.
  15. */
  16. public function authorize(): bool
  17. {
  18. return true;
  19. }
  20. /**
  21. * Get the validation rules that apply to the request.
  22. *
  23. * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
  24. */
  25. public function rules(): array
  26. {
  27. return [
  28. 'name' => 'required|max:100',
  29. 'code' => [
  30. 'required',
  31. 'max:45',
  32. Rule::unique('assets')
  33. ->where($this->userCompanyWhere())
  34. ->ignore($this->route()->parameter('asset')),
  35. ],
  36. 'status' => [
  37. 'required',
  38. new Enum(AssetStatus::class),
  39. ],
  40. 'owner' => [
  41. 'required',
  42. Rule::exists('users', 'id')
  43. ->where($this->userCompanyWhere()),
  44. ],
  45. 'address' => 'max:255',
  46. 'group_id' => [
  47. 'required',
  48. Rule::exists('asset_groups', 'id')
  49. ->where($this->userCompanyWhere()),
  50. ],
  51. 'geo_address_code' => 'max:255',
  52. 'acl' => 'required',
  53. 'whitelist' => [
  54. 'array',
  55. function ($attribute, $value, $fail) {
  56. $userCount = User::where("company_id", Auth::user()->company_id)->whereIn('id', $value)->count();
  57. if ($userCount != count($value)) {
  58. $fail('The selected user is invalid.');
  59. }
  60. }
  61. ],
  62. 'latitude' => 'numeric',
  63. 'longitude' => 'numeric',
  64. 'parent_id' => [
  65. $this->parentIdExistsRule(),
  66. ]
  67. ];
  68. }
  69. protected function parentIdExistsRule()
  70. {
  71. // 如果 parent_id 不为 0,返回 exists 规则
  72. if ($this->input('parent_id') != 0) {
  73. return Rule::exists('assets', 'id')->where($this->userCompanyWhere());
  74. }
  75. // 如果 parent_id 为 0,返回空数组以跳过 exists 验证
  76. return [];
  77. }
  78. public function attributes()
  79. {
  80. return [
  81. 'name' => __("fields.name"),
  82. 'code' => __("fields.code"),
  83. 'acl' => __("fields.acl"),
  84. 'address' => __("fields.address"),
  85. 'owner' => __("fields.owner"),
  86. 'status' => __("fields.status"),
  87. ];
  88. }
  89. }