You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.5 KiB

2 years ago
  1. <?php
  2. namespace App\Rules;
  3. use Illuminate\Contracts\Database\Query\Builder;
  4. use Illuminate\Contracts\Validation\Rule;
  5. use Illuminate\Support\Facades\DB;
  6. class UniqueRule implements Rule
  7. {
  8. private string $table;
  9. private string $field;
  10. private Builder $query;
  11. public function __construct(string $table, string $field)
  12. {
  13. $this->table = $table;
  14. $this->field = $field;
  15. $this->query = DB::table($this->table);
  16. }
  17. /**
  18. * Determine if the validation rule passes.
  19. *
  20. * @param string $attribute
  21. * @param mixed $value
  22. * @return bool
  23. * @throws \Throwable
  24. */
  25. public function passes($attribute, $value)
  26. {
  27. throw_if(is_array($value), 'UniqueRule won\'t work in array values like ' . $attribute);
  28. return empty($value) ? true : !$this->query->where($this->field, $value)->exists();
  29. }
  30. public function withoutTrashed($deletedAtColumn = 'deleted_at'): UniqueRule
  31. {
  32. $this->query->whereNull($deletedAtColumn);
  33. return $this;
  34. }
  35. public function where($column, $value): UniqueRule
  36. {
  37. $this->query->where($column, $value);
  38. return $this;
  39. }
  40. public function ignore($id): UniqueRule
  41. {
  42. if (empty($id)) {
  43. return $this;
  44. }
  45. $this->query->whereNot('id', $id);
  46. return $this;
  47. }
  48. /**
  49. * Get the validation error message.
  50. *
  51. * @return string
  52. */
  53. public function message()
  54. {
  55. return 'select value already exists.';
  56. }
  57. }