CreateOrUpdateRequest.php 3.0 KB

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