SystemMediaCategoryRequest.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Http\Requests;
  3. use Illuminate\Database\Query\Builder;
  4. use Illuminate\Support\Arr;
  5. use Illuminate\Validation\Rule;
  6. class SystemMediaCategoryRequest extends FormRequest
  7. {
  8. public function rules()
  9. {
  10. $cate = $this->route('system_media_category');
  11. $id = optional($cate)->id;
  12. $rules = [
  13. 'name' => [
  14. 'bail',
  15. 'required',
  16. 'max:20',
  17. Rule::unique('system_media_categories', 'name')
  18. ->where(function (Builder $query) use ($cate) {
  19. // 有传 parent_id,即同时修改名称和 parent_id,
  20. // 所以以传入的 parent_id 为准
  21. // 没有传,则已当前分类的 parent_id 为准
  22. $parentId = $this->input('parent_id') ?? optional($cate)->parent_id;
  23. return $query->where('parent_id', $parentId);
  24. })
  25. ->ignore($id),
  26. ],
  27. 'parent_id' => 'exists:system_media_categories,id',
  28. ];
  29. if ($this->isMethod('put')) {
  30. $rules = Arr::only($rules, $this->keys());
  31. }
  32. if ($this->input('parent_id') == 0) {
  33. $rules['parent_id'] = 'nullable';
  34. }
  35. return $rules;
  36. }
  37. public function attributes()
  38. {
  39. return [
  40. 'parent_id' => '父级分类',
  41. 'name' => '名称',
  42. ];
  43. }
  44. public function messages()
  45. {
  46. return [
  47. 'name.unique' => '同级下 :attribute 已经存在',
  48. ];
  49. }
  50. }