Unique.php 1.6 KB

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