diff --git a/src/Html.php b/src/Html.php
index a9c88e0..27dfbd0 100644
--- a/src/Html.php
+++ b/src/Html.php
@@ -2,6 +2,7 @@
namespace Spatie\Html;
+use BackedEnum;
use DateTimeImmutable;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Http\Request;
@@ -26,6 +27,7 @@
use Spatie\Html\Elements\Select;
use Spatie\Html\Elements\Span;
use Spatie\Html\Elements\Textarea;
+use UnitEnum;
class Html
{
@@ -591,7 +593,9 @@ protected function old($name, $value = null)
// has a model assigned and there aren't old input items,
// try to retrieve a value from the model.
if (is_null($value) && $this->model && empty($this->request->old())) {
- $value = data_get($this->model, $name) ?? '';
+ $value = ($value = data_get($this->model, $name)) instanceof UnitEnum
+ ? $this->getEnumValue($value)
+ : $value;
}
return $this->request->old($name, $value);
@@ -647,4 +651,17 @@ protected function formatDateTime($value, $format)
return $value;
}
}
+
+ /**
+ * Get the value from the given enum.
+ *
+ * @param \UnitEnum|\BackedEnum $value
+ * @return string|int
+ */
+ protected function getEnumValue($value)
+ {
+ return $value instanceof BackedEnum
+ ? $value->value
+ : $value->name;
+ }
}
diff --git a/tests/Html/ModelFormTest.php b/tests/Html/ModelFormTest.php
index 671e7bb..3120775 100644
--- a/tests/Html/ModelFormTest.php
+++ b/tests/Html/ModelFormTest.php
@@ -1,5 +1,8 @@
' .
@@ -8,3 +11,21 @@
$this->html->modelForm([])
);
});
+
+it('returns an enum value from a name with an enum cast in the model', function () {
+ withModel(['relation' => ['role' => Role::Admin]]);
+ assertHtmlStringEqualsHtmlString(
+ '',
+ $this->html->text('relation[role]')
+ );
+
+ withModel(['select' => Status::Pending]);
+ assertHtmlStringEqualsHtmlString(
+ '',
+ $this->html->select('select', Status::asSelectArray())->render()
+ );
+});
diff --git a/tests/Stubs/Role.php b/tests/Stubs/Role.php
new file mode 100644
index 0000000..8e1a07a
--- /dev/null
+++ b/tests/Stubs/Role.php
@@ -0,0 +1,10 @@
+