spatie / laravel-enum

Laravel support for spatie/enum
https://spatie.be/open-source
MIT License
344 stars 37 forks source link

I cant do new model() #81

Closed BaraoVlask closed 3 years ago

BaraoVlask commented 3 years ago

I don't know what I'm doing wrong.

The model

class Operadora extends Model
{
    use HasFactory;

    protected $table = 'operadoras';

    protected $fillable = [
        'url',
        'nome',
        'senha',
        'status',
        'usuario',
    ];

    protected $casts = [
        'status' => StatusEnum::class,
    ];
}

The enum class

/**
 * @method static self ativa()
 * @method static self inativa()
 */
class StatusEnum extends \Spatie\Enum\Enum
{
    protected static function values(): array
    {
        return [
            'ativa' => 1,
            'inativa' => 0,
        ];
    }

    protected static function labels(): array
    {
        return [
            'ativa' => 'Ativa',
            'inativa' => 'Inativa',
        ];
    }
}

The usage

$arrOperadoras = json_decode($storage->get($file), true);
foreach ($arrOperadoras as $operadora) {
//array:5 [
//  "url" => "string"
//  "nome" => "string"
//  "senha" => "string"
//  "status" => "ativa"
//  "usuario" => "string"
//]
    $objOperadora = new Operadora($operadora);
    $objOperadora->save();
}

Already tried

$objOperadora = new Operadora();
$objOperadora->fill($operadora);
$objOperadora->save();

The error

Too few arguments to function Spatie\Enum\Enum::__construct(), 0 passed in /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 1341 and exactly 1 expected
Gummibeer commented 3 years ago

Hey, it seems like you are using the wrong base enum class. class StatusEnum extends \Spatie\Enum\Enum you have to extend the laravel specific enum use Spatie\Enum\Laravel\Enum;.

BaraoVlask commented 3 years ago

Tanks for the help