Laravel 8 模型允许的列值

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

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:

枚举:

  1. enum ServerStatus: string
  2. {
  3. case Active = 'active';
  4. case Pending = 'pending';
  5. }

Model:

模型:

  1. use App\Enums\ServerStatus;
  2. protected $casts = [
  3. 'status' => ServerStatus::class,
  4. ]

Validation:

验证:

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

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

英文:

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

Enum:

  1. enum ServerStatus: string
  2. {
  3. case Active = 'active';
  4. case Pending = 'pending';
  5. }

Model:

  1. use App\Enums\ServerStatus;
  2. protected $casts = [
  3. 'status' => ServerStatus::class,
  4. ];

Validation:

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

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:

确定