| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- namespace Illuminate\Database\Eloquent\Concerns;
- use Illuminate\Database\Eloquent\ModelNotFoundException;
- use Illuminate\Support\Str;
- trait HasUlids
- {
- /**
- * Initialize the trait.
- *
- * @return void
- */
- public function initializeHasUlids()
- {
- $this->usesUniqueIds = true;
- }
- /**
- * Get the columns that should receive a unique identifier.
- *
- * @return array
- */
- public function uniqueIds()
- {
- return [$this->getKeyName()];
- }
- /**
- * Generate a new ULID for the model.
- *
- * @return string
- */
- public function newUniqueId()
- {
- return strtolower((string) Str::ulid());
- }
- /**
- * Retrieve the model for a bound value.
- *
- * @param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation $query
- * @param mixed $value
- * @param string|null $field
- * @return \Illuminate\Contracts\Database\Eloquent\Builder
- *
- * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
- */
- public function resolveRouteBindingQuery($query, $value, $field = null)
- {
- if ($field && in_array($field, $this->uniqueIds()) && ! Str::isUlid($value)) {
- throw (new ModelNotFoundException)->setModel(get_class($this), $value);
- }
- if (! $field && in_array($this->getRouteKeyName(), $this->uniqueIds()) && ! Str::isUlid($value)) {
- throw (new ModelNotFoundException)->setModel(get_class($this), $value);
- }
- return parent::resolveRouteBindingQuery($query, $value, $field);
- }
- /**
- * Get the auto-incrementing key type.
- *
- * @return string
- */
- public function getKeyType()
- {
- if (in_array($this->getKeyName(), $this->uniqueIds())) {
- return 'string';
- }
- return $this->keyType;
- }
- /**
- * Get the value indicating whether the IDs are incrementing.
- *
- * @return bool
- */
- public function getIncrementing()
- {
- if (in_array($this->getKeyName(), $this->uniqueIds())) {
- return false;
- }
- return $this->incrementing;
- }
- }
|