You need to enable JavaScript to run this app. Laravel 8 如何设置枚举FileTypes所有值为字段默认值
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8 如何设置枚举FileTypes所有值为字段默认值

解决方案

第一步:修正枚举文件的笔误

你的FileTypes枚举存在两处值定义错误,先修正避免后续逻辑异常:

<?php

namespace App\Enums;

use BenSampo\Enum\Enum;

final class FileTypes extends Enum
{
    const JPG =   'jpg';
    const PNG =   'png'; // 原代码错误写为ps
    const AI = 'ai';
    const PS = 'ps';
    const PDF = 'pdf'; // 原代码错误写为psd
    const BMP = 'bmp';
    const IDDD = 'iddd';
}

第二步:调整迁移文件逻辑

首先明确:MySQL原生enum类型仅支持存储指定列表中的单个值,无法直接将所有枚举值设为默认值。如果你需要默认允许所有文件类型,说明该字段需要存储多值,建议改用json类型存储,修改后的迁移代码如下:

<?php
    
use App\Enums\FileTypes;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
    
class AddFielsToProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('products', function (Blueprint $table) {
            // 用json类型存储多值,通过BenSampo Enum内置的getValues()方法直接获取所有枚举值作为默认
            $table->json('allowed_file_types')->default(json_encode(FileTypes::getValues()));
            $table->integer('max_file_upload');
            $table->integer('min_jpg_dpi');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn('allowed_file_types');
            $table->dropColumn('max_file_upload');
            $table->dropColumn('min_jpg_dpi');
        });
    }
}

第三步:配置模型类型转换(可选但推荐)

在Product模型中添加字段类型转换,方便直接操作数组格式的允许文件类型:

protected $casts = [
    'allowed_file_types' => 'array',
    // 其他已有cast配置
];

特殊场景:仅需存储单个文件类型

如果你实际需求是字段仅存单个值,只是误表述为默认所有值,直接用getValues()方法获取枚举列表,指定对应默认值即可:

// 示例默认值为jpg,可根据需求替换为其他枚举常量
$table->enum('allowed_file_types', FileTypes::getValues())->default(FileTypes::JPG);

内容的提问来源于stack exchange,提问作者Công Nguyễn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 01:48:03