CreateOrUpdateRequest.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. ];
  65. }
  66. public function attributes()
  67. {
  68. return [
  69. 'name' => __("fields.name"),
  70. 'code' => __("fields.code"),
  71. 'acl' => __("fields.acl"),
  72. 'address' => __("fields.address"),
  73. 'owner' => __("fields.owner"),
  74. 'status' => __("fields.status"),
  75. ];
  76. }
  77. }