Laravel 9中如何提交TinyMCE富文本HTML至数据库?
Laravel 9 + TinyMCE 6 富文本HTML提交丢失问题解决
问题场景
使用Laravel 9搭配TinyMCE 6开发时,通过普通POST/GET请求或AJAX提交表单,前端控制台显示body参数包含完整HTML标签(如body=%3Cp%3E%3Cstrong%3Ecustom%3C%2Fstrong%3E%3C%2Fp%3E),但后端控制器用dd($request)查看时,body字段仅保留纯文本(如custom),无法将完整HTML内容存储到数据库。
核心原因及解决步骤
1. 关闭Laravel的自动HTML清理
Laravel默认的请求处理会自动过滤HTML标签以防范XSS攻击,这是内容丢失的主要原因。可以通过以下方式允许HTML内容:
- 直接获取原始输入:在控制器中使用
$request->input('body', '', false),第三个参数设为false即可跳过HTML清理; - 表单验证放行:如果使用表单请求验证类,不要给
body字段添加strip_tags规则,或使用raw规则允许原始内容。
2. 确保TinyMCE内容同步到textarea
需确保TinyMCE的内容正确同步到对应的textarea,建议手动指定编辑器实例执行同步,避免DOM加载顺序导致的同步失败:
tinymce.get('tinymcecreate').save();
3. 检查数据库字段类型
确认blog表的body字段类型为TEXT或LONGTEXT,避免因VARCHAR长度限制截断HTML内容。
4. 模型填充白名单验证
确保Blog模型的$fillable数组包含body字段,否则Eloquent的create方法会忽略该字段:
protected $fillable = ['image', 'title', 'description', 'body', 'type'];
修改后的完整代码示例
后端控制器代码
public function admin_blog_create(Request $request) { $file_name = time() . '.' . $request->image->getClientOriginalExtension(); $request->image->move(public_path('image/tinymce'), $file_name); // 获取未清理的HTML内容 $body = $request->input('body', '', false); $tiny = [ 'image' => $file_name, 'title' => $request->title, 'description' => $request->description, 'body' => $body, 'type' => 'blog', ]; Blog::create($tiny); return response()->json(['status'=>true, 'message' => $body]); }
前端AJAX代码(优化版)
$('#addpromotionform').on('submit', function(e) { e.preventDefault(); // 手动同步TinyMCE内容到textarea tinymce.get('tinymcecreate').save(); var formData = new FormData(this); $.ajax({ type: "post", url:'{{ route("admin.blog.create") }}', data: formData, cache: false, contentType: false, processData: false, success: function(data) { console.log('success: ' + data.message); }, error: function(error) { console.log('error: ', error); } }); });
Blog模型代码
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Blog extends Model { use HasFactory; protected $fillable = ['image', 'title', 'description', 'body', 'type']; }
内容的提问来源于stack exchange,提问作者DIY engineer
相关产品推荐
相关产品推荐

