Laravel 枚举转换错误调用未定义的方法 App\\Enums\\UserType::from()

Laravel Enum casting error Call to undefined method App\\Enums\\UserType::from()

当我尝试将属性从我的模型转换为我的枚举之一时,它抛出一个错误:

Call to undefined method App\Enums\UserType::from()

我找不到关于所需 find() 方法的任何信息。

我遵循了说明 here

我的枚举UserType:

namespace App\Enums;

enum UserType
{
    case CUSTOMER;
    case PARTNER;
    case ADMIN;
}

我的用户模型:

namespace App\Models;

use App\Enums\UserType;
use FaarenTech\LaravelCustomUuids\Interfaces\HasCustomUuidInterface;
use FaarenTech\LaravelCustomUuids\Models\UuidModel;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableInterface;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableInterface;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Auth\Authenticatable;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Auth\Passwords\CanResetPassword;

class User extends UuidModel implements
    AuthorizableInterface,
    AuthenticatableInterface,
    CanResetPasswordInterface,
    HasCustomUuidInterface
{
    use
        HasApiTokens,
        HasFactory,
        Notifiable,
        Authenticatable,
        Authorizable,
        CanResetPassword,
        MustVerifyEmail,
        SoftDeletes;

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'type' => UserType::class
    ];
}

您需要将每个枚举映射到一个标量值(int、float、string、bool),这样 Laravel 可以从(数据库存储的)值 -> 枚举转换。

例如

enum UserType: string
{
    case CUSTOMER = 'CUSTOMER';
    case PARTNER = 'PARTNER';
    case ADMIN = 'ADMIN';
}

参见 PHP 中的 Backed Enums

Backed enums implement an internal BackedEnum interface, which exposes two additional methods:

from(int|string): self will take a scalar and return the corresponding Enum Case. If one is not found, it will throw a ValueError. This is mainly useful in cases where the input scalar is trusted and a missing enum value should be considered an application-stopping error.