CreateOrUpdateRequest.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. 'nullable',
  48. 'sometimes',
  49. Rule::exists('asset_groups', 'id')
  50. ->where($this->userCompanyWhere()),
  51. ],
  52. 'geo_address_code' => 'max:255',
  53. 'acl' => 'required',
  54. 'whitelist' => [
  55. 'array',
  56. function ($attribute, $value, $fail) {
  57. $userCount = User::where("company_id", Auth::user()->company_id)->whereIn('id', $value)->count();
  58. if ($userCount != count($value)) {
  59. $fail('The selected user is invalid.');
  60. }
  61. }
  62. ],
  63. 'latitude' => 'numeric',
  64. 'longitude' => 'numeric',
  65. 'parent_id' => [
  66. $this->parentIdExistsRule(),
  67. ]
  68. ];
  69. }
  70. protected function parentIdExistsRule()
  71. {
  72. // 如果 parent_id 不为 0,返回 exists 规则
  73. if ($this->input('parent_id') != 0) {
  74. return Rule::exists('assets', 'id')->where($this->userCompanyWhere());
  75. }
  76. // 如果 parent_id 为 0,返回空数组以跳过 exists 验证
  77. return [];
  78. }
  79. public function attributes()
  80. {
  81. return [
  82. 'name' => __("fields.name"),
  83. 'code' => __("fields.code"),
  84. 'acl' => __("fields.acl"),
  85. 'address' => __("fields.address"),
  86. 'owner' => __("fields.owner"),
  87. 'status' => __("fields.status"),
  88. ];
  89. }
  90. }