I have an Enum like:
<?php
namespace App\Models\helpers\Enums;
enum ComissionamentoVendedor: string
{
case Faturamento = 'No faturamento';
case Pagamento = 'Após o pagamento pelo cliente';
}
And I have a model that uses this Enum
...
public $casts = [
'comissionamento_momento' => ComissionamentoVendedor::class,
];
...
But when I try to save it I get an error:
$vendedor = new Vendedor;
$vendedor->fill($atributos);
$vendedor->save();
The error is ErrorException: Attempt to read property "value" on string
It happens on the file vendor/illuminate/database/Eloquent/Concerns/HasAttributes.php:951
protected function setEnumCastableAttribute($key, $value)
{
// $value here is a string, a valid value from ComissionamentoVendedor Enum, sent by the frontend but looks like Laravel expects to be an Enum
$this->attributes[$key] = isset($value) ? $value->value : null;
}
Am I doing something wrong? I'm actually using Lumen 8.3.3.
Unless you can upgrade the Illuminate libraries being used in your application you don't have the feature of the ability to have the cast get an Enum from a string for you; you will have to pass an Enum. You can get the Enum you need from a string using the from method:
$enum = ComissionamentoVendedor::from($value);
If you are not sure if this value is actually a valid value for the Enum you can use the tryFrom method:
$enum = CommissionamentoVendedor::tryFrom($value) ?? $defaultEnum;
PHP.net Manual - Language Reference - Enumerations - Backed enumerations
Github - Laravel Framework - Commit - [8.x] Enum casts accept backed values committed on Nov 15, 2021
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With