Laravel 8 模型允许的列值

huangapple go评论51阅读模式
英文:

Laravel 8 model alowed values for column

问题

我需要检查表列的允许值,类似于ENUM。是否可以在模型实体级别设置它?

英文:

I need to chcek alowed values for table column like ENUM. Is it possible to set it up on model entity level?

答案1

得分: 1

Enum:

枚举:

enum ServerStatus: string
{
    case Active = 'active';
    case Pending = 'pending';
}

Model:

模型:

use App\Enums\ServerStatus;

protected $casts = [
    'status' => ServerStatus::class,
]

Validation:

验证:

use App\Enums\ServerStatus;
use Illuminate\Validation\Rules\Enum;

$request->validate([
    'status' => [new Enum(ServerStatus::class)],
])

请注意,这是一些代码示例,用于在 Laravel 中创建枚举并将其用于模型和验证。您可以参考提供的链接以获取更多详细信息。

英文:

You need to create an Enum and use it within your Model, and here's how you can do it:

Enum:

enum ServerStatus: string
{
    case Active = 'active';
    case Pending = 'pending';
}

Model:

use App\Enums\ServerStatus;
 
protected $casts = [
    'status' => ServerStatus::class,
];

Validation:

use App\Enums\ServerStatus;
use Illuminate\Validation\Rules\Enum;
 
$request->validate([
    'status' => [new Enum(ServerStatus::class)],
]);

https://www.php.net/manual/en/language.enumerations.backed.php

https://laravel.com/docs/8.x/eloquent-mutators#enum-casting

https://laravel.com/docs/8.x/validation#rule-enum

huangapple
  • 本文由 发表于 2023年6月15日 18:25:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481560.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定