ListRequest.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Http\Requests;
  3. use Illuminate\Foundation\Http\FormRequest;
  4. class ListRequest extends FormRequest
  5. {
  6. public function rules(): array
  7. {
  8. return [
  9. 'sort_by' => 'sometimes|string',
  10. 'sort_order' => 'sometimes|in:asc,desc',
  11. 'page' => 'sometimes|integer|min:1',
  12. 'per_page' => 'sometimes|integer|min:1|max:100',
  13. ];
  14. }
  15. /**
  16. * 自定义错误消息
  17. * @return string[]
  18. */
  19. public function messages(): array
  20. {
  21. return [
  22. 'search.max' => '搜索关键字不能超过 100 个',
  23. // 'filters.status.in' => '状态必须是「0:启用」或「1:禁用」',
  24. // 'sort_by.in' => '排序字段只能是 id、create_time 或 update_time',
  25. 'sort_order.in' => '排序方向必须是(asc:升序、desc:降序)',
  26. 'page.min' => '当前页最小数字为 1',
  27. 'per_page.min' => '每页数量最小数字为 1',
  28. ];
  29. }
  30. public function getSearch(): string
  31. {
  32. return $this->input('search') ?? '';
  33. }
  34. public function getFilters(): array
  35. {
  36. return $this->input('filters', []);
  37. }
  38. public function getSort(): array
  39. {
  40. return [
  41. 'sort_by' => $this->input('sort_by', 'id'),
  42. 'sort_order' => $this->input('sort_order', 'desc'),
  43. ];
  44. }
  45. public function getPerPage(): int
  46. {
  47. return $this->input('per_page', 20);
  48. }
  49. }