You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Factory填充JSON数据至数据库时多双引号问题求助

解决Laravel Factory填充JSON数据时出现多余双引号的问题

问题原因

你在Factory里直接写了转义后的JSON字符串,如果你的blocks字段是数据库的JSON/JSONB类型,Laravel会自动对传入内容做JSON序列化,这就导致了双重转义,最终存入数据库的内容带有多余双引号。

解决方案

根据字段类型,选择以下两种方式之一:

方式1:字段为JSON/JSONB类型(推荐)

直接传入PHP数组,Laravel会自动帮你转换成正确的JSON格式存入数据库:

public function definition(): array
{
    return [
        'title' => 'Home',
        'slug' => '/',
        'layout' => 'default',
        'blocks' => [
            [
                'type' => 'cta',
                'data' => [
                    'title' => 'NxtPress.org',
                    'subtext' => 'Welcome to NxtPress.org || Managed with ♥ by Nxt Invent Solutions',
                    'buttontext' => 'Visit Website',
                    'buttonurl' => 'https://nxtinvent.com',
                    'linktype' => '_BLANK'
                ]
            ]
        ],
    ];
}

方式2:字段为普通字符串类型

如果blocks字段是普通VARCHAR/TEXT类型,需要传入未转义的JSON字符串,或者用json_encode处理数组:

public function definition(): array
{
    return [
        'title' => 'Home',
        'slug' => '/',
        'layout' => 'default',
        // 方法A:直接写未转义的JSON字符串
        'blocks' => '[{"type":"cta","data": {"title":"NxtPress.org","subtext":"Welcome to NxtPress.org || Managed with ♥ by Nxt Invent Solutions","buttontext":"Visit Website","buttonurl":"https://nxtinvent.com","linktype":"_BLANK"}}]',
        // 方法B:用json_encode处理数组(更可靠,避免手动写错格式)
        // 'blocks' => json_encode([
        //     [
        //         'type' => 'cta',
        //         'data' => [
        //             'title' => 'NxtPress.org',
        //             'subtext' => 'Welcome to NxtPress.org || Managed with ♥ by Nxt Invent Solutions',
        //             'buttontext' => 'Visit Website',
        //             'buttonurl' => 'https://nxtinvent.com',
        //             'linktype' => '_BLANK'
        //         ]
        //     ]
        // ]),
    ];
}

修改完Factory代码后,重新运行Seeder即可:

php artisan db:seed --class=你的Seeder类名

内容的提问来源于stack exchange,提问作者Maxx nagar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:52:15