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

Laravel中如何将表单数据以JSON格式存储至MySQL数据库?

把Laravel表单数据以JSON格式存储到MySQL的完整流程

嘿,作为Laravel新手,这个需求其实很好实现,我给你拆解从Blade模板到数据库存储的每一步,保证你能跟着做出来~

1. 先准备数据库表(迁移)

首先你需要一个带JSON类型字段的数据表,用来存表单的JSON数据。创建一个迁移文件:

php artisan make:migration create_forms_table

打开生成的迁移文件,修改up()方法,添加JSON字段:

public function up()
{
    Schema::create('forms', function (Blueprint $table) {
        $table->id();
        $table->json('form_data'); // 这个就是专门存JSON的字段
        $table->timestamps();
    });
}

然后运行迁移,创建数据表:

php artisan migrate

2. 创建并配置模型

生成对应的数据模型:

php artisan make:model Form

打开app/Models/Form.php,设置可填充字段和类型转换——类型转换是关键,它能自动帮你把数组转成JSON存进数据库,取出来又自动转成数组,不用手动调用json_encode/json_decode:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Form extends Model
{
    // 允许批量赋值的字段
    protected $fillable = ['form_data'];

    // 自动完成数组与JSON的双向转换
    protected $casts = [
        'form_data' => 'array',
    ];
}

3. 修改Blade表单

把你原来的表单改成Laravel风格,注意几个关键点:

  • 表单方法用POST
  • 提交地址用Laravel路由(别用静态的action_page.php啦)
  • 必须加@csrf令牌防止跨站请求伪造

修改后的Blade代码:

<div class="container">
    <form action="{{ route('form.store') }}" method="POST">
        @csrf <!-- 这个一定要加,不然Laravel会拒绝请求 -->
        
        <label for="fname">First Name</label>
        <input type="text" id="fname" name="firstname" placeholder="First Name">

        <label for="lname">Last Name</label>
        <input type="text" id="lname" name="lastname" placeholder="Last Name">

        <label for="subject">Subject</label>
        <textarea id="subject" name="subject" placeholder="Subject" style="height:300px"></textarea>

        <input type="submit" value="Submit">
    </form>
</div>

4. 设置路由

打开routes/web.php,添加一条POST路由,指向后面要创建的控制器方法:

use App\Http\Controllers\FormController;

Route::post('/submit-form', [FormController::class, 'store'])->name('form.store');

5. 创建控制器并写存储逻辑

生成处理表单提交的控制器:

php artisan make:controller FormController

打开app/Http/Controllers/FormController.php,编写store方法,接收表单数据并存储:

namespace App\Http\Controllers;

use App\Models\Form;
use Illuminate\Http\Request;

class FormController extends Controller
{
    public function store(Request $request)
    {
        // 可选:添加表单验证,确保必填字段不为空
        $request->validate([
            'firstname' => 'required|string',
            'lastname' => 'required|string',
            'subject' => 'required|string',
        ]);

        // 把表单数据存成JSON(因为模型设置了casts,直接传数组就行)
        Form::create([
            'form_data' => $request->only(['firstname', 'lastname', 'subject'])
        ]);

        // 提交成功后返回上一页并提示
        return back()->with('success', '表单已成功提交!');
    }
}

6. 验证效果

提交表单后,你去数据库的forms表里查看form_data字段,会看到和你期望一致的JSON格式:

{ "firstname":"John", "lastname":"Immanuel", "subject":"This is a test msg" }

如果要在代码里取出数据使用,直接像访问数组一样操作就行:

$form = Form::find(1);
echo $form->form_data['firstname']; // 输出 John

这样整个流程就走完啦,是不是很清晰?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:11:38