Laravel 8模型层面能否设置数据表列(如ENUM)的允许值?
在Laravel 8模型层面配置ENUM类型列的允许值检查
当然可以在Laravel 8的模型层面实现ENUM类型列的允许值校验,下面是几种常用的实现方式:
方法一:定义常量+监听模型保存事件
先在模型中定义该ENUM列的所有允许值常量,再通过模型的saving事件在保存前自动校验:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use InvalidArgumentException; class Post extends Model { // 定义ENUM允许的常量值 const STATUS_DRAFT = 'draft'; const STATUS_PUBLISHED = 'published'; const STATUS_ARCHIVED = 'archived'; public const ALLOWED_STATUSES = [self::STATUS_DRAFT, self::STATUS_PUBLISHED, self::STATUS_ARCHIVED]; protected static function boot() { parent::boot(); // 监听保存事件,校验状态值 static::saving(function ($model) { if (!in_array($model->status, self::ALLOWED_STATUSES)) { throw new InvalidArgumentException( "状态值无效,允许的值为: " . implode(', ', self::ALLOWED_STATUSES) ); } }); } }
方法二:使用自定义类型转换(Cast)
通过自定义Cast类,在赋值时自动校验值的合法性:
- 创建自定义Cast类:
namespace App\Casts; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use InvalidArgumentException; class EnumStatusCast implements CastsAttributes { // 定义允许的ENUM值 protected $allowedValues = ['draft', 'published', 'archived']; public function get($model, $key, $value, $attributes) { return $value; } public function set($model, $key, $value, $attributes) { if (!in_array($value, $this->allowedValues)) { throw new InvalidArgumentException( "无效的状态值,允许的值为: " . implode(', ', $this->allowedValues) ); } return $value; } }
- 在模型中绑定该Cast到对应列:
namespace App\Models; use App\Casts\EnumStatusCast; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $casts = [ 'status' => EnumStatusCast::class, ]; }
方法三:重写模型save方法结合验证器
利用Laravel自带的验证器,在模型保存前做校验:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Validation\ValidationException; use Illuminate\Support\Facades\Validator; class Post extends Model { public const ALLOWED_STATUSES = ['draft', 'published', 'archived']; public function save(array $options = []) { $validator = Validator::make($this->attributes, [ 'status' => 'required|in:' . implode(',', self::ALLOWED_STATUSES), ]); if ($validator->fails()) { throw new ValidationException($validator); } return parent::save($options); } }
内容的提问来源于stack exchange,提问作者Čamo
相关产品推荐
相关产品推荐

