1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace App\Http\Requests\API\Asset;
- use App\Http\Requests\RuleHelper;
- use App\Models\Enums\AssetStatus;
- use App\Models\User;
- use Illuminate\Foundation\Http\FormRequest;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Validation\Rule;
- use Illuminate\Validation\Rules\Enum;
- class CreateOrUpdateRequest extends FormRequest
- {
- use RuleHelper;
- /**
- * Determine if the user is authorized to make this request.
- */
- public function authorize(): bool
- {
- return true;
- }
- /**
- * Get the validation rules that apply to the request.
- *
- * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
- */
- public function rules(): array
- {
- return [
- 'name' => 'required|max:100',
- 'code' => [
- 'required',
- 'max:45',
- Rule::unique('assets')
- ->where($this->userCompanyWhere())
- ->ignore($this->route()->parameter('asset')),
- ],
- 'status' => [
- 'required',
- new Enum(AssetStatus::class),
- ],
- 'owner' => [
- 'required',
- Rule::exists('users', 'id')
- ->where($this->userCompanyWhere()),
- ],
- 'address' => 'max:255',
- 'group_id' => [
- 'nullable',
- 'sometimes',
- Rule::exists('asset_groups', 'id')
- ->where($this->userCompanyWhere()),
- ],
- 'geo_address_code' => 'max:255',
- 'acl' => 'required',
- 'whitelist' => [
- 'array',
- function ($attribute, $value, $fail) {
- $userCount = User::where("company_id", Auth::user()->company_id)->whereIn('id', $value)->count();
- if ($userCount != count($value)) {
- $fail('The selected user is invalid.');
- }
- }
- ],
- 'latitude' => 'numeric',
- 'longitude' => 'numeric',
- 'parent_id' => [
- $this->parentIdExistsRule(),
- ]
- ];
- }
- protected function parentIdExistsRule()
- {
- // 如果 parent_id 不为 0,返回 exists 规则
- if ($this->input('parent_id') != 0) {
- return Rule::exists('assets', 'id')->where($this->userCompanyWhere());
- }
- // 如果 parent_id 为 0,返回空数组以跳过 exists 验证
- return [];
- }
- public function attributes()
- {
- return [
- 'name' => __("fields.name"),
- 'code' => __("fields.code"),
- 'acl' => __("fields.acl"),
- 'address' => __("fields.address"),
- 'owner' => __("fields.owner"),
- 'status' => __("fields.status"),
- ];
- }
- }
|