Unique.php 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Illuminate\Validation\Rules;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Unique
  5. {
  6. use DatabaseRule;
  7. /**
  8. * The ID that should be ignored.
  9. *
  10. * @var mixed
  11. */
  12. protected $ignore;
  13. /**
  14. * The name of the ID column.
  15. *
  16. * @var string
  17. */
  18. protected $idColumn = 'id';
  19. /**
  20. * Ignore the given ID during the unique check.
  21. *
  22. * @param mixed $id
  23. * @param string|null $idColumn
  24. * @return $this
  25. */
  26. public function ignore($id, $idColumn = null)
  27. {
  28. if ($id instanceof Model) {
  29. return $this->ignoreModel($id, $idColumn);
  30. }
  31. $this->ignore = $id;
  32. $this->idColumn = $idColumn ?? 'id';
  33. return $this;
  34. }
  35. /**
  36. * Ignore the given model during the unique check.
  37. *
  38. * @param \Illuminate\Database\Eloquent\Model $model
  39. * @param string|null $idColumn
  40. * @return $this
  41. */
  42. public function ignoreModel($model, $idColumn = null)
  43. {
  44. $this->idColumn = $idColumn ?? $model->getKeyName();
  45. $this->ignore = $model->{$this->idColumn};
  46. return $this;
  47. }
  48. /**
  49. * Convert the rule to a validation string.
  50. *
  51. * @return string
  52. */
  53. public function __toString()
  54. {
  55. return rtrim(sprintf('unique:%s,%s,%s,%s,%s',
  56. $this->table,
  57. $this->column,
  58. $this->ignore ? '"'.$this->ignore.'"' : 'NULL',
  59. $this->idColumn,
  60. $this->formatWheres()
  61. ), ',');
  62. }
  63. }