GithubHelp home page GithubHelp logo

laravel-enum's Introduction

Laravel support for spatie/enum

Latest Version on Packagist License Postcardware

PHP from Packagist Build Status Total Downloads

This package provides extended support for our spatie/enum package in Laravel.

Installation

You can install the package via composer:

composer require spatie/laravel-enum

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Usage

// a Laravel specific base class
use Spatie\Enum\Laravel\Enum;

/**
 * @method static self DRAFT()
 * @method static self PREVIEW()
 * @method static self PUBLISHED()
 * @method static self ARCHIVED()
 */
final class StatusEnum extends Enum {}

Model Attribute casting

Chances are that if you're working in a Laravel project, you'll want to use enums within your models. This package provides two custom casts and the \Spatie\Enum\Laravel\Enum also implements the \Illuminate\Contracts\Database\Eloquent\Castable interface.

use Illuminate\Database\Eloquent\Model;

class TestModel extends Model
{
    protected $casts = [
        'status' => StatusEnum::class,
        'nullable_enum' => StatusEnum::class.':nullable',
        'array_of_enums' => StatusEnum::class.':collection',
        'nullable_array_of_enums' => StatusEnum::class.':collection,nullable',
    ];
}

By using the casts the casted attribute will always be an instance of the given enum.

$model = new TestModel();
$model->status = StatusEnum::DRAFT();
$model->status->equals(StatusEnum::DRAFT());

Validation Rule

This package provides a validation rule to validate your request data against a given enumerable.

use Spatie\Enum\Laravel\Rules\EnumRule;

$rules = [
    'status' => new EnumRule(StatusEnum::class),
];

This rule validates that the value of status is any possible representation of the StatusEnum.

But you can also use the simple string validation rule definition:

$rules = [
    'status' => [
        'enum:'.StatusEnum::class,
    ],
];

If you want to customize the failed validation messages you can publish the translation file.

php artisan vendor:publish --provider="Spatie\Enum\Laravel\EnumServiceProvider" --tag="translation"

We pass several replacements to the translation key which you can use.

  • attribute - the name of the validated attribute
  • value - the actual value that's validated
  • enum - the full class name of the wanted enumerable
  • other - a comma separated list of all possible values - they are translated via the enums array in the translation file

Request Data Transformation

A common scenario is that you receive an enumerable value as part of your request data. To let you work with it as a real enum object you can transform request data to an enum in a similar way to the model attribute casting.

Request macro

There is a request macro available which is the base for the other possible ways to cast request data to an enumerable.

$request->transformEnums($enumCastRules);

This is an example definition of all possible request enum castings. There are three predefined keys available as constants on Spatie\Enum\Laravel\Http\EnumRequest to cast enums only in specific request data sets. All other keys will be treated as independent enum casts and are applied to the combined request data set.

use Spatie\Enum\Laravel\Http\EnumRequest;

$enums = [
    // cast the status key independent of it's data set
    'status' => StatusEnum::class,
    // cast the status only in the request query params
    EnumRequest::REQUEST_QUERY => [
        'status' => StatusEnum::class,
    ],
    // cast the status only in the request post data
    EnumRequest::REQUEST_REQUEST => [
        'status' => StatusEnum::class,
    ],
    // cast the status only in the request route params
    EnumRequest::REQUEST_ROUTE => [
        'status' => StatusEnum::class,
    ],
];

You can call this macro yourself in every part of your code with access to a request instance. Most commonly you will do this in your controller action if you don't want to use one of the other two ways.

Form Requests

Form requests are the easiest way to cast the data to an enum.

use Illuminate\Foundation\Http\FormRequest;
use Spatie\Enum\Laravel\Http\Requests\TransformsEnums;
use Spatie\Enum\Laravel\Rules\EnumRule;

class StatusFormRequest extends FormRequest
{
    use TransformsEnums;

    public function rules(): array
    {
        return [
            'status' => new EnumRule(StatusEnum::class),
            'properties.level' => new EnumRule(LevelEnum::class),
        ];
    }

    public function enums(): array
    {
        return [
            'status' => StatusEnum::class,
            'properties.level' => LevelEnum::class,
        ];
    }
}

The request data transformation is done after validation via the FormRequest::passedValidation() method. If you define your own passedValidation() method you have to call the request macro transformEnums() yourself.

protected function passedValidation()
{
    $this->transformEnums($this->enums());

    // ...
}

Route Binding

Beside using form requests, you can also use route binding. Similar Laravel's Route Model Binding, it automatically inject enum instances into your route action.

Implicit Binding

To use implicit route binding, be sure add Spatie\Enum\Laravel\Http\Middleware\SubstituteBindings middleware. For example, add it in your app\Http\Kernel.php:

protected $middlewareGroups = [
    'web' => [
        // ...
        \Spatie\Enum\Laravel\Http\Middleware\SubstituteEnumBindings::class,
    ],
];

Use a type-hinted variable name that matches route segment to use implicit route binding.

Route::get('/posts/{status}', function (StatusEnum $status) {
    return $status;
});

Explicit Binding

To have an explicit binding, there is a Route::enum() macro. It's important that your route/group uses the \Illuminate\Routing\Middleware\SubstituteBindings middleware. This middleware is enabled by default for the web route group.

Route::enum('status', StatusEnum::class);
Route::get('/posts/{status}', function (Request $request) {
    return $request->route('status');
});

Enum Make Command

We provide an artisan make command which allows you to quickly create new enumerables.

php artisan make:spatie-enum StatusEnum

You can use --method option to predefine some enum values - you can use them several times.

Faker Provider

It's very likely that you will have a model with an enum attribute and you want to generate random enum values in your model factory. Because doing so with default faker is a lot of copy'n'paste we've got you covered with a faker provider Spatie\Enum\Laravel\Faker\FakerEnumProvider. The static register() method is only a little helper - you can for sure register the provider the default way $faker->addProvider(new FakerEnumProvider).

The faker methods itself are inherited from the base packages Faker Provider.

Testing

composer test
composer test-coverage

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-enum's People

Contributors

adrianmrn avatar binotaliu avatar brendt avatar chuoke avatar craigpotter avatar dpetrovaliev avatar freekmurze avatar gaelreyrol avatar gummibeer avatar ju5t avatar justinaskav avatar maldechavda avatar mansoorkhan96 avatar nicolasbeauvais avatar nielsvanpach avatar patinthehat avatar rubenvanassche avatar skullbock avatar supertassu avatar telkins avatar thecaliskan avatar xewl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

laravel-enum's Issues

Creating New Model - No Value Defined for Enum

I have :

  • Package model with package_type attribute
  • PackageTypeEnum class

I already cast the package_type attribute with PackageTypeEnum class, it's working properly as expected, but I got an issue while creating new model, unable to assign value directly.
In my views, I loaded the values and labels of PackageTypeEnum using toArray() static method then make them as select option field. When I try to create new Package it respond an error for package_type field

  • views
<select name="package_type" id="__package_typeAddPackage">
    <option value="" selected disabled>
        {{ __('Select Type') }}
    </option>
    @foreach ($packageTypes as $value => $label)
        <option value="{{ $value }}">
            {{ $label }}
        </option>
    @endforeach
</select>
  • store method
...
    public function store(StoreRequest $request)
    {
            $data = $request->validated();

            $package = new Package();
            $package->package_type = $data['package_type'];
...
  • the errors
There's no value 2 defined for enum App\Enums\PackageTypeEnum, ...

What's the best practice and/or How to deal with this case, when we want to directly assign the value to our Enum cast attributes?
Do I have to create new method that returns every single value of my enum static method?

Thanks

Enum validation rule

Would it make sense to add one or more custom validation rules to validate request input?

Hability to blacklist static methods

I know this issue has been discussed in spatie/enum#28 but with the recent addition of the Castable interface in Laravel I believe this needs to be revised.

I've created custom casters to Enum classes and would like to be able to make them implement the Castable interface which required a public static castUsing() method.

Currently this is impossible with Enum classes because static methods are assumed to be enum values. An @ignoreEnum doc annotation, like suggested in the issue, would solve this while still maintaining backwards compatibility.

BadMethodCallException: There's no value Some College defined for enum App\Domain\Admission\Enums\HighestEducationEnum, consider adding it in the docblock definition. in ..vendor\spatie\enum\src\Enum.php:157

I got this weird behaviour, values in snake case (some_elementary, some_high_school) returns BadMethodCallException, while a single word like elementary, vocational works perfectly fine.

Enum:

<?php

namespace App\Domain\Admission\Enums;

use Spatie\Enum\Enum;

/**
 * @method static self some_elementary()
 * @method static self elementary()
 * @method static self some_high_school()
 * @method static self high_school()
 * @method static self vocational()
 * @method static self some_college()
 * @method static self bachelor_degree()
 * @method static self master_degree()
 * @method static self professional_degree()
 * @method static self doctoral_degree()
 * @method static self other()
 */
class HighestEducationEnum extends Enum
{
    protected static function values(): array
    {
        return [
            'some_elementary' => 1,
            'elementary' => 2,
            'some_high_school' => 3,
            'high_school' => 4,
            'vocational' => 5,
            'some_college' => 6,
            'bachelor_degree' => 7,
            'master_degree' => 8,
            'professional_degree' => 9,
            'doctoral_degree' => 10,
            'other' => 11,
        ];
    }

    protected static function labels(): array
    {
        return [
            'some_elementary' => 'Some Elementary',
            'elementary' => 'Elementary',
            'some_high_school' => 'Some High School',
            'high_school' => 'High School',
            'vocational' => 'Vocational',
            'some_college' => 'Some College',
            'bachelor_degree' => 'Bachelor Degree',
            'master_degree' => 'Master Degree',
            'professional_degree' => 'Professional Degree',
            'doctoral_degree' => 'Doctoral Degree',
            'other' => 'Other',
        ];
    }
}

Stack Trace:

Stack trace:
#0 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\spatie\enum\src\Enum.php(102): Spatie\Enum\Enum->__construct('Some College')
#1 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\app\Domain\Admission\Services\AdmissionService.php(137): Spatie\Enum\Enum::from('Some College')
#2 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\app\Http\Livewire\Admission\Components\AdmissionFamilyForm.php(113): App\Domain\Admission\Services\AdmissionService->storeFamily(Object(App\Domain\Admission\Dto\CreateAdmissionFamilyDto), 61)
#3 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Collections\Traits\EnumeratesValues.php(236): App\Http\Livewire\Admission\Components\AdmissionFamilyForm->App\Http\Livewire\Admission\Components\{closure}(Array, 0)
#4 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\app\Http\Livewire\Admission\Components\AdmissionFamilyForm.php(112): Illuminate\Support\Collection->each(Object(Closure))
#5 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(36): App\Http\Livewire\Admission\Components\AdmissionFamilyForm->submit()
#6 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Container\Util.php(41): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#7 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(93): Illuminate\Container\Util::unwrapIfClosure(Object(Closure))
#8 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(35): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#9 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\livewire\livewire\src\ComponentConcerns\HandlesActions.php(149): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array)
#10 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\livewire\livewire\src\HydrationMiddleware\PerformActionCalls.php(36): Livewire\Component->callMethod('submit', Array, Object(Closure))
#11 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\livewire\livewire\src\LifecycleManager.php(89): Livewire\HydrationMiddleware\PerformActionCalls::hydrate(Object(App\Http\Livewire\Admission\Components\AdmissionFamilyForm), Object(Livewire\Request))
#12 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\livewire\livewire\src\Connection\ConnectionHandler.php(13): Livewire\LifecycleManager->hydrate()
#13 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\livewire\livewire\src\Controllers\HttpConnectionHandler.php(19): Livewire\Connection\ConnectionHandler->handle(Array)
#14 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php(46): Livewire\Controllers\HttpConnectionHandler->__invoke('admission.compo...')
#15 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Routing\Route.php(259): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(Livewire\Controllers\HttpConnectionHandler), '__invoke')
#16 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Routing\Route.php(205): Illuminate\Routing\Route->runController()
#17 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Routing\Router.php(799): Illuminate\Routing\Route->run()
#18 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(141): Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#19 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php(50): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#20 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))
#21 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php(78): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#22 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#23 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php(49): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#24 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#25 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(121): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#26 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(64): Illuminate\Session\Middleware\StartSession->handleStatefulRequest(Object(Illuminate\Http\Request), Object(Illuminate\Session\Store), Object(Closure))
#27 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#28 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#29 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#30 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php(67): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#31 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#32 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\stancl\tenancy\src\Middleware\IdentificationMiddleware.php(36): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#33 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\stancl\tenancy\src\Middleware\InitializeTenancyByDomain.php(37): Stancl\Tenancy\Middleware\IdentificationMiddleware->initializeTenancy(Object(Illuminate\Http\Request), Object(Closure), 'catsu.localhost')
#34 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Stancl\Tenancy\Middleware\InitializeTenancyByDomain->handle(Object(Illuminate\Http\Request), Object(Closure))
#35 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(116): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#36 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Routing\Router.php(798): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#37 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Routing\Router.php(777): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#38 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Routing\Router.php(741): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
#39 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Routing\Router.php(730): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#40 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(200): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#41 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(141): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#42 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\livewire\livewire\src\DisableBrowserCache.php(19): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#43 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Livewire\DisableBrowserCache->handle(Object(Illuminate\Http\Request), Object(Closure))
#44 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#45 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull->handle(Object(Illuminate\Http\Request), Object(Closure))
#46 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TrimStrings.php(36): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#47 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\TrimStrings->handle(Object(Illuminate\Http\Request), Object(Closure))
#48 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#49 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
#50 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance.php(86): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#51 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance->handle(Object(Illuminate\Http\Request), Object(Closure))
#52 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Http\Middleware\HandleCors.php(49): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#53 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Http\Middleware\HandleCors->handle(Object(Illuminate\Http\Request), Object(Closure))
#54 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Http\Middleware\TrustProxies.php(39): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#55 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Http\Middleware\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
#56 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(116): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#57 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(175): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#58 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(144): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#59 C:\Users\Isaac\Desktop\Dev\Laravel\unilink\source\public\index.php(51): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))

Not nullable enums break Laravel Nova create resource

Hello,

first of all, i will explain the situation:
i have an eloquent model that has not nullable enum fields.
This model has a Laravel nova resource related to it.
am having the NotNullableEnumField exception thrown when i try to create a new model instance via Laravel nova.

There is my cast on the eloquent model:

protected $casts = [
    'status' => ModelStatusEnum::class,
    'type' => ModelTypeEnum::class,
];

There is the related Laravel nova fields

Select::make('Type')
      ->options(ModelTypeEnum::toArray())
      ->rules('required', new EnumRule(ModelTypeEnum::class))
      ->displayUsingLabels(),

Select::make('Status')
    ->options(ModelStatusEnum::toArray())
    ->rules('required', new EnumRule(ModelStatusEnum::class))
    ->displayUsingLabels(),

There is the exception thrown on creating a new instance:
Spatie\Enum\Laravel\Exceptions\NotNullableEnumField(code: 0): Field type on model ... is not nullable

this is my setup:
php: 8.0.1
spatie/laravel-enum: 2.5.2
Laravel: 8.78.1
Laravel nova: 3.30

Thank you in advance.

Form request validated data is not casted to enum

Hello 👋,

When casting enums in a Form Request, only the data payload in the Request instance is getting cast. So if following best practice and getting the data with the validated method in a controller, the original pre-cast data will be returned.

class Controller
{
    public function index(MyFormRequest $request)
    {  
        $request->validated()); // Doesn't return cast data

        $request->get('status'); // Return cast data
    }
}

As a fix, I created an enhanced TransformsEnums trait implementing the following method:

public function withValidator(Validator $validator)
{
    $validator->after(function (Validator $validator) {
        $data = $validator->getData();

        /** @var Enum $enumClass */
        foreach ($this->enums() as $key => $enumClass) {
            Arr::set($data, $key, $enumClass::from($this[$key]));
        }

        $validator->setData($data);
    });
}

Do you think that this is something that could be added to the package?

I could draft a PR on this, but given the native enum support on PHP 8.1 I wanted to make sure you would continue the maintenance of laravel-enum before working on it.

Cheers.

mark enum values as obsolete/disabled?

Is it possible to mark certain enum values as obsolete / disabled?

Use case example:

  • last year there were company A, B, C and I have an enum for them
  • this year company A and C have merged and formed a new company: companyAandC, so I add that one to the enum
  • I don't want to remove companyA and companyC (because still valid for old records), but for new records I want to check against only the valid values.

As a conceptual example:

/**
 * @method static self companyA()
 * @method static self companyB()
 * @method static self companyC()
 * @method static self companyAandC()
 */
class CompanyEnum extends Enum
{
    protected static function obsolete(): array
    {
        return [
          'companyA' => 'merged with company C',
          'companyC' => 'merged with company A',
        ];
    }
}

CompanyEnum::toValues(); // ['companyA', 'companyB', 'companyC', 'companyAandC']

CompanyEnum::toValidValues(); // ['companyB', 'companyAandC']
CompanyEnum::toObsolete(); // ['companyA' => 'merged with company C, 'companyC' => 'merged with company A']

Get Label in Response

I am trying to achieve a functionality which allows to get label in response for the enum.

Person.php

protected $casts = [
        'id' => 'integer',
        'first_name' => 'string',
        'last_name' => 'string',
        'email' => 'string',
        'type' => PersonEnum::class
    ];

PersonController.php

public function show(Request $request, $personId)
{
return Person::findOrFail($id);
}

PersonEnum.php

<?php

namespace App\Enums;

use Spatie\Enum\Laravel\Enum;

/**
 * @method static self Customer()
 * @method static self Supplier()
 */
final class PersonEnum extends Enum
{
    protected static function values(): array
    {
        return [
            'Customer' => 1,
            'Supplier' => 2
        ];
    }

    protected static function labels(): array
    {
        return [
            'Customer' => 'Customer',
            'Supplier' => 'Supplier',
        ];
    }
}

Expected JSON response
"type": "Customer" or "type": "Supplier"

Current Response:
"type": 1,

How to use FakerEnumProvider?

I would like to register this provider in AppServiceProvider:

$this->app->singleton(Faker::class, function ($app) {
            $faker = new Faker();
            $faker->addProvider(new FakerEnumProvider($faker));

            return $faker;
        });

Result:
Unknown format "text"
It seems it cannot find the default Faker factories/methods, any tips?

Thanks!

Minor documentation issue

In the readme.md it states on line 34/35:

// a Laravel specific base class
use Spatie\Enum\Laravel\Enum;

Shouldn't that be:

// a Laravel specific base class
use Spatie\Enum\Enum;

The first one gave me an error in PHPStorm saying that the Enum class didn't exists. Or am is missing something here?

v1 => v2 and v2 => v3 upgrade guides

I'm attempting to upgrade a project from version 1.6.1 of this package to the latest version, but I can't find a list of breaking changes or any recommendations to work around them.

A full upgrade guide would be awesome, but even just some basic info (e.g. for any model that uses the HasEnum attribute, we recommend doing X) would be very helpful.

Thanks!

Trait 'Spatie\Enum\HasEnums' not found

In README.md the example shows:

use Spatie\Enum\HasEnums;

but I believe this should be:

use Spatie\Enum\Laravel\HasEnums;

I can make a PR if you can confirm that's correct (and a PR is easier than you correcting it directly).

Unexpected validation exception in Livewire

I'm trying to implement this package in a Livewire component. Some code to illustrate:

Our Enum:

/**
 * @method static self BUSINESS()
 * @method static self HOUSEHOLD()
 */
final class CustomerType extends Enum
{
    protected static function values(): array
    {
        return [
            'BUSINESS' => 'business',
            'HOUSEHOLD' => 'household',
        ];
    }
}

Our Model:

class Customer extends Model
{
...
    protected $casts = [
        'type' => CustomerType::class,
    ];
...

Our Livewire component:

class CustomerEdit extends Component
{
...
    public $customer;

    protected function rules()
    {
        return [
            'customer.type' => 'enum:'.CustomerType::class,

...

I manipulate customer.type with a radio button. When I @json this on the rendered page, I get the type as a string. But as soon as I validate it, I get (thanks Ray!):

TypeError {#1745 ▼
  #message: "Only string and integer are allowed values for enum Domain\Customers\Enums\CustomerType."
  #code: 0
  #file: "my_app/vendor/spatie/enum/src/Enum.php"
  #line: 87
  trace: {▶}
}

This is coming from passes(..) in the EnumRule. It sets the value with:

$this->asEnum($value);

But $value appears to be the CustomerType enum. It's not a string or integer. That's why it fails. I'm not sure why this happens. Should this be fixed in this package or are we doing something wrong?

Unable to groupBy a Collection Using an Enum as a Criteria when Casting

Hi there,

Sorry if I'm doing something wrong but there's a problem when using an enum as model attribute and the attribute is used in the method groupBy of a Eloquent Collection. Example:

The model:

use Illuminate\Database\Eloquent\Model;

class TestModel extends Model
{
    protected $casts = [
        'status' => StatusEnum::class,
    ];
}

The problem with groupBy:

$testModels = TestModel::all;

$testModels->groupBy('status');

The return is:

TypeError
array_key_exists(): Argument #1 ($key) must be a valid array offset type in vendor/laravel/framework/src/Illuminate/Collections/Collection.php:445

If I remove the cast from the model, it works fine, using the value as array key. Any suggestions?

Thanks!

I cant do new model()

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

Can't install with Enum package

When I try to install this package along side the Spatie/Enum package, I get the following error:

  Problem 1
    - Installation request for spatie/enum (locked at 3.1.1, required as ^3.1) -> satisfiable by spatie/enum[3.1.1].
    - spatie/laravel-enum 1.6.0 requires spatie/enum ^2.3 -> satisfiable by spatie/enum[v2.x-dev].
    - spatie/laravel-enum 1.6.1 requires spatie/enum ^2.3 -> satisfiable by spatie/enum[v2.x-dev].
    - Conclusion: don't install spatie/enum v2.x-dev
    - Installation request for spatie/laravel-enum ^1.6 -> satisfiable by spatie/laravel-enum[1.6.0, 1.6.1].

EnumRule issue with different Enums, same value

Hi,
When we have 2 different enums and 1 rule EnumRule(EmailScopeEnum::class

/**
@method static self DEFAULT()
**/
EmailScopeEnum {
}

/**
@method static self DEFAULT()
**/
PhoneScopeEnum {
}

When we try to check rule against PhoneScopeEnum::DEFAULT() it's working, because DEFAULT can be resolved also in EmailScopeEnum

I fix this by changing passes function in EnumRule

public function passes($attribute, $value): bool
    {
        $this->attribute = $attribute;
        $this->value = $value;

        if ($value instanceof $this->enum) {
            return true;
        }

        if ($value instanceof Enum && !$value instanceof $this->enum) {
            return false;
        }

        try {
            $this->asEnum($value);

            return true;
        } catch (Throwable $ex) {
            return false;
        }
    }

Command incorrect in README

Within the README.md, the following artisan command is given as an example:
php artisan enum:make StatusEnum

However, this seems to be incorrect, and the correct command is the other way around:
php artisan make:enum StatusEnum

I've created the following PR to fix this typo:
#35

Enum scopes

Add support for Model::query()->whereEnum(ModelStatus::DRAFT())

Make command gives incomplete output

I just started using this package and after installation I created a new Enum using the php artisan make:enum FooEnum command.

It created the Enum just fine however the command output is incomplete and only shows:

created successfully.

Instead of what I think it should have been:

FooEnum created successfully.

Collection validation

I have a list os value that I have encapsulated as enum. It's something like this:

/**
 * @method static self VALUE1()
 * @method static self VALUE2()
 * @method static self VALUE3()
 */
final class FooEnum extends Enum
{}

And I can select one or more os theses values, I'm trying to validade if in the values I receive in the controller are valid.
The array I receive is something like this:

$many_foo=[
    0 => 'VALUE1',
    1 => 'VALUE23'
];

And my validation is something like this:

$request->validate([
   'many_foo' => ['required', new EnumRule(FooEnum::class)
]

BadMethodCallException with numerical enum values

I have a UserTypeEnum with 2 values, Provider and Client. I had already created the database schema with tiny integers for this field so I wanted to set the values to be numerical.

I could not see an example in the documentation for this package but I saw an example of using numbers in the base enum package.

My class is below. When I call the request transformation function, it throws a BadMethodCallException which I think is because of the strict comparison between values. My form is a simple POST form which is submitting a string "1" which does not match the numerical 1 in the values array.

The error is as follows:

BadMethodCallException
There's no value 1 defined for enum App\Enums\UserTypeEnum, consider adding it in the docblock definition.

Enum example:

/**
 * @method static self PROVIDER()
 * @method static self CLIENT()
 */
final class UserTypeEnum extends Enum
{
    protected static function values(): array
    {
        return [
            'PROVIDER' => 1,
            'CLIENT' => 2,
        ];
    }
}

This is how I am calling the transformEnums method.

$request->transformEnums($this->enumCastRules());

Below is the enum cast rules I am using.

private function enumCastRules()
{
    return [
        'type' => UserTypeEnum::class,
    ];
}

My form field:

<input type="radio" name="type" id="type_provider" value="{{ \App\Enums\UserTypeEnum::PROVIDER() }}">

Translator Class not found inside labels method

when i use translator function inside labels method an exception is thrown with a message that the Translator class does not exist, any Ideas?

public static function labels()
{
   return [
       'ACTIVE' => __('app.active'),
    ];
}
   

How to get enum label?

i write in UserStatusEnum
protected static function labels(): array { return [ 'free' => 'свободен', 'holiday' => 'выходной', 'meet_appointed' => 'встреча назначена', 'meet_accepted' => 'встреча принята', 'on_meet' => 'на встрече', 'in_pair' => 'в паре' ]; }
then i used
Auth::user()->status->label
and get this error
Undefined property: App\Enums\UserStatusEnum::$label

Enum collection support for`set` column type.

Hi, I have the following case:

I have a table with a column type set which is comma-separated values ex. "MALE,FEMALE".
Would be great if there is an additional cast for a column with that column type.

Is is possible to use Enums on $attributes?

I want to replace this code

protected $attributes = [
        'status' => self::STATUS_DRAFT,
    ];

But as far as I see, you can't.

protected $attributes = [
        'status' => StatusEnum::draft(),
    ];

That throws error

Custom validation message for EnumValue

Hy,

I have a Form Request with a custom validation rule:

$rules = [ 'input.value' => ['required', new EnumValue(ValueEnum::class, false)], ];

Validation works fine but the message received is ambiguous:

The value you have entered is invalid.

Is there a way to change this message to include at least the attribute in it?

use Laravel Enum in combination with database migration (and: how to list possible values)

Two part question:

  1. is it possible to create a collection of possible values for an enum? I see the Model $casts, but how would I achieve it outside a Model, e.g. in tinker?
  2. how do I use Laravel Enum in combination with a database migration?

This to avoid hardcoding e.g.

            $table->enum('status', ['draft','approved','archived']);

Could be I am misunderstanding the package, in which case: apologies!

model attribute cast array of enums

We have a multiselect/checkboxes - every of these options is a value of the same enum.

foreach($enum->values() as $value) {
    echo '<checkbox value="'.$value.'"/>';
}

And on the model we save this in a JSON column. like we already introduced the :nullable flag - how about being able to add a array flag or even better use the [] notation behind the enum class name.

Because the new Laravel 7 object custom casts work pretty much the same like our current notation we should/could add this feature before dropping Laravel 6 support.

MyEnum::class
MyEnum::class.':nullable'
// options for new array cast  feature
MyEnum::class.'[]:nullable'
MyEnum::class.':nullable,array'

The expected result would be an array of enum instances Enumerable[].

const MAP_VALUE working incorrect

My enum:

<?php

namespace App\Enums;

use Spatie\Enum\Enum;

/**
 * @method static self WAITING_FOR_COMPANY_REPLY()
 * @method static self INVITE_INTERVIEW()
 * @method static self ACCEPT_INTERVIEW()
 * @method static self REJECT_INTERVIEW()
 * @method static self COMPANY_REJECT()
 */
class ApplyStatusEnum extends Enum
{
    const MAP_VALUE = [
        'WAITING_FOR_COMPANY_REPLY' => 1,
        'ACCEPT_INTERVIEW' => 2,
    ];
}

When I use \App\Models\Apply::where('status', 1)->first()->status->getName() it return ACCEPT_INTERVIEW.
It looks like laravel-enum use index 1 map to ACCEPT_INTERVIEW instance of use value 1 and map to WAITING_FOR_COMPANY_REPLY.

What did I do wrong?

packagist

Add this package to packagist. Even without a version it will make it a bit easier to test it.

Nullable not working as expected

The nullable cast gets validated as being an actual string value when using:

protected $casts = [
   'status' => SomeStatusEnum::class.':nullable'
];

Exception: (spatie\Enum class) [expects a $value, "nullable" gets passed]
There's no value "nullable" defined for enum SomeStatusEnum, consider adding it in the docblock definition.

Removing the :nullable cast, also returns the exception that it's not passing (the expected number of) parameters
( see also spatie/enum#70 )

When I change it to eg. SomeStatusEnum::class.:collection,nullable the above occurs with constructor $value "collection"

getIndex return value when used in a factory

Hello,

When using the enums inside a factory it always return the value and not the index.

Example :

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
        'account_type' => AccountType::USER()->getIndex(),
    ];
});
>>> factory('App\User')->make();
=> App\User {#3082
     name: "Roxanne Terry-test",
     email: "[email protected]",
     email_verified_at: "2020-03-23 14:02:45",
     account_type: "USER",

the same happens when I try to override the field :

>>> factory('App\User')->make(['account_type' => App\Enums\AccountType::USER()->getIndex()]);
=> App\User {#3069
     name: "Ms. Vella Buckridge DVM",
     email: "[email protected]",
     email_verified_at: "2020-03-23 14:04:31",
     account_type: "USER",
   }

But if I use a default value in my migration it work as expected

$table->integer('account_type')->unsigned()->default(AccountType::USER()->getIndex());
>>> factory('App\User')->create();
=> App\User {#3070
     name: "Prof. Sylvester Bartoletti Sr.",
     email: "[email protected]",
     email_verified_at: "2020-03-23 14:09:37",
     updated_at: "2020-03-23 14:09:37",
     created_at: "2020-03-23 14:09:37",
     id: 1,
   }
>>> App\User::find(1);
=> App\User {#3079
     id: "1",
     name: "Prof. Sylvester Bartoletti Sr.",
     email: "[email protected]",
     email_verified_at: "2020-03-23 14:09:37",
     account_type: "0",
     created_at: "2020-03-23 14:09:37",
     updated_at: "2020-03-23 14:09:37",
   }

edit: I use laravel-enums so maybe related idk.

Compatibility issue with Laravel 10

I'm trying to use spatie/laravel-enum in my Laravel 10 project, but I'm encountering an error related to compatibility. I believe there is a conflict between the requirements of spatie/laravel-enum and Laravel 10. Can you please help me resolve this issue?

{
    "require": {
        "php": "^8.1",
        "laravel/framework": "^10.0",
        "illuminate/support": "^9.0",
        "spatie/laravel-enum": "^3.0"
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - illuminate/support[v8.0.0, ..., v8.11.2] require php ^7.3 -> your php version (8.1.13) does not satisfy that requirement.
    - Root composer.json requires laravel/framework ^10.0 -> satisfiable by laravel/framework[10.x-dev].
    - spatie/laravel-enum[3.0.0, ..., 3.0.1] require illuminate/support ^8.0 || ^9.0 -> satisfiable by illuminate/support[v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev].
    - Only one of these can be installed: illuminate/support[v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev], laravel/framework[10.x-dev]. laravel/framework replaces illuminate/support and thus cannot coexist with it.
    - Root composer.json requires spatie/laravel-enum ^3.0 -> satisfiable by spatie/laravel-enum[3.0.0, 3.0.1].

Validation message not resolved when using 'enum:' rule instead of EnumRule

Hey guys, great work on this package 😄

I noticed that I wasn't getting proper validation messages every time I was using 'attribute' => 'enum:'.StatusEnum::class. The message returned is 'validation.enum'.
Instead, if I use 'attribute' => new EnumRule(StatusEnum::class),, the validation message is correct.

I would've opened a PR if I knew exactly how to fix this 😄. I implemented two tests to prove this is a real issue, but I'm not sure they're good tests, so this may be just a config issue.

Here's a test that fails:

    /** @test */
    public function it_returns_validation_message_when_using_validation_rule_in_string_form()
    {
        Lang::addLines([
            'validation.enum' => ':value',
        ], Lang::getLocale(), 'enum');

        $validator = Validator::make([
            'attribute' => 'foobar',
        ], [
            'attribute' => 'enum:'.StatusEnum::class,
        ]);

        $this->assertEquals('foobar', $validator->errors()->first('attribute'));
    }

and a test that passes:

    /** @test */
    public function it_returns_validation_message_when_using_validation_rule_in_enum_rule_form()
    {
        Lang::addLines([
            'validation.enum' => ':value',
        ], Lang::getLocale(), 'enum');

        $validator = Validator::make([
            'attribute' => 'foobar',
        ], [
            'attribute' => new EnumRule(StatusEnum::class),
        ]);

        $this->assertEquals('foobar', $validator->errors()->first('attribute'));
    }

I'm using PHP 7.4, the latest version of the package.
Thanks and all the best 😄

Does laravel-enum v2 require laravel-framework v8?

I am trying to install spatie/laravel-enum 2.1 in my project running laravel-framework 7.19.1. (full error below)
composer require spatie/laravel-enum --update-with-dependencies

My guess is that spatie/laravel-enum requires illuminate/http ^8.0 and that is only available in Laravel 8? If so, does that mean that laravel-enum v2 is only compatible with laravel-framework v8?

  Problem 1
    - Installation request for spatie/laravel-enum ^2.1 -> satisfiable by spatie/laravel-enum[2.1.0].
    - Conclusion: remove laravel/framework v7.19.1
    - Conclusion: don't install laravel/framework v7.19.1
    - spatie/laravel-enum 2.1.0 requires illuminate/http ^8.0 -> satisfiable by illuminate/http[8.x-dev, v8.0.0, v8.0.1, v8.0.2, v8.0.3, v8.0.4, v8.1.0, v8.10.0, v8.11.0, v8.11.1, v8.11.2, v8.12.0, v8.12.1, v8.2.0, v8.3.0, v8.4.0, v8.5.0, v8.6.0, v8.7.0, v8.7.1, v8.8.0, v8.9.0].
    - don't install illuminate/http 8.x-dev|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.0.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.0.1|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.0.2|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.0.3|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.0.4|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.1.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.10.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.11.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.11.1|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.11.2|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.12.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.12.1|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.2.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.3.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.4.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.5.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.6.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.7.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.7.1|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.8.0|don't install laravel/framework v7.19.1
    - don't install illuminate/http v8.9.0|don't install laravel/framework v7.19.1
    - Installation request for laravel/framework (locked at v7.19.1, required as ^7.0) -> satisfiable by laravel/framework[v7.19.1].

HasEnums trait collides with HasTranslations trait

Using HasEnums trait with HasTranslations trait on the same Model, cause collision error:

Trait method setAttribute has not been applied, because there are collisions with other trait methods on Model

How can I solve the problem in order to use both Traits in the Model?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.