InteractsWithDictionary.php 912 B

1234567891011121314151617181920212223242526272829303132333435
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations\Concerns;
  3. use BackedEnum;
  4. use InvalidArgumentException;
  5. use UnitEnum;
  6. trait InteractsWithDictionary
  7. {
  8. /**
  9. * Get a dictionary key attribute - casting it to a string if necessary.
  10. *
  11. * @param mixed $attribute
  12. * @return mixed
  13. *
  14. * @throws \InvalidArgumentException
  15. */
  16. protected function getDictionaryKey($attribute)
  17. {
  18. if (is_object($attribute)) {
  19. if (method_exists($attribute, '__toString')) {
  20. return $attribute->__toString();
  21. }
  22. if ($attribute instanceof UnitEnum) {
  23. return $attribute instanceof BackedEnum ? $attribute->value : $attribute->name;
  24. }
  25. throw new InvalidArgumentException('Model attribute value is an object but does not have a __toString method.');
  26. }
  27. return $attribute;
  28. }
  29. }