HasUuids.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Concerns;
  3. use Illuminate\Database\Eloquent\ModelNotFoundException;
  4. use Illuminate\Support\Str;
  5. trait HasUuids
  6. {
  7. /**
  8. * Initialize the trait.
  9. *
  10. * @return void
  11. */
  12. public function initializeHasUuids()
  13. {
  14. $this->usesUniqueIds = true;
  15. }
  16. /**
  17. * Get the columns that should receive a unique identifier.
  18. *
  19. * @return array
  20. */
  21. public function uniqueIds()
  22. {
  23. return [$this->getKeyName()];
  24. }
  25. /**
  26. * Generate a new UUID for the model.
  27. *
  28. * @return string
  29. */
  30. public function newUniqueId()
  31. {
  32. return (string) Str::orderedUuid();
  33. }
  34. /**
  35. * Retrieve the model for a bound value.
  36. *
  37. * @param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation $query
  38. * @param mixed $value
  39. * @param string|null $field
  40. * @return \Illuminate\Contracts\Database\Eloquent\Builder
  41. *
  42. * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
  43. */
  44. public function resolveRouteBindingQuery($query, $value, $field = null)
  45. {
  46. if ($field && in_array($field, $this->uniqueIds()) && ! Str::isUuid($value)) {
  47. throw (new ModelNotFoundException)->setModel(get_class($this), $value);
  48. }
  49. if (! $field && in_array($this->getRouteKeyName(), $this->uniqueIds()) && ! Str::isUuid($value)) {
  50. throw (new ModelNotFoundException)->setModel(get_class($this), $value);
  51. }
  52. return parent::resolveRouteBindingQuery($query, $value, $field);
  53. }
  54. /**
  55. * Get the auto-incrementing key type.
  56. *
  57. * @return string
  58. */
  59. public function getKeyType()
  60. {
  61. if (in_array($this->getKeyName(), $this->uniqueIds())) {
  62. return 'string';
  63. }
  64. return $this->keyType;
  65. }
  66. /**
  67. * Get the value indicating whether the IDs are incrementing.
  68. *
  69. * @return bool
  70. */
  71. public function getIncrementing()
  72. {
  73. if (in_array($this->getKeyName(), $this->uniqueIds())) {
  74. return false;
  75. }
  76. return $this->incrementing;
  77. }
  78. }