Laravel控制器中如何直接填充并保存JSON数组列properties?
问题解决:Laravel中JSON数组列
properties无法填充的问题 问题描述
在Laravel项目的Hunter控制器store()和update()方法中,尝试用可空JSON数组类型的properties列存储其他迁移列的所有信息,但数据库中properties列始终无法保存数据。调试时dd($hunter)能看到对应值,但数据库无数据写入。
代码现状
迁移文件
public function up() { Schema::create('hunters', function (Blueprint $table) { $table->id(); $table->string('name_hunter', 50); $table->integer('year_hunter'); $table->decimal('height_hunter', 3,2); $table->decimal('weight_hunter', 5,2); $table->string('type_hunter', 30); $table->string('type_nen', 30); $table->string('type_sangue', 3); $table->timestamp('register_date')->useCurrent(); $table->timestamp('data_updated')->useCurrent()->useCurrentOnUpdate(); $table->json('properties')->nullable(); }); }
Hunter模型
protected $fillable = ['name_hunter', 'year_hunter', 'height_hunter', 'weight_hunter', 'type_hunter', 'type_nen', 'type_blood']; protected $casts = [ 'properties' => 'array' ];
Hunter控制器
public function store(HunterRequest $request) { $hunter = new HunterModel(); $validations = $request->validated(); $hunter['properties'] = json_encode($validations); HunterModel::create($validations); return redirect('/'); } public function update(HunterRequest $request, $id) { $hunter = HunterModel::find($id); $validations = $request->validated(); $hunter['properties'] = json_encode($validations); HunterModel::where('id',$id)->update($validations); return redirect('/'); }
问题原因
- 批量赋值权限未开放:模型
$fillable数组未包含properties字段,导致批量赋值时该字段被过滤。 - 手动JSON编码多余:模型已通过
$casts配置将properties转为数组类型,Laravel会自动处理JSON编码和解码,手动json_encode会导致存储的是字符串而非JSON数组。 - 控制器逻辑错误:虽然给实例赋值了
properties,但最终执行创建/更新操作时传入的是原始$validations数组,未包含properties字段。
修复方案
1. 更新Hunter模型的$fillable
将properties加入批量允许赋值的列表:
protected $fillable = ['name_hunter', 'year_hunter', 'height_hunter', 'weight_hunter', 'type_hunter', 'type_nen', 'type_blood', 'properties']; protected $casts = [ 'properties' => 'array' ];
2. 修改store方法
将properties字段加入$validations数组后执行创建:
public function store(HunterRequest $request) { $validations = $request->validated(); // 直接传入数组,Laravel自动编码为JSON $validations['properties'] = $validations; HunterModel::create($validations); return redirect('/'); }
3. 修改update方法
同样将properties加入$validations数组后执行更新:
public function update(HunterRequest $request, $id) { $validations = $request->validated(); $validations['properties'] = $validations; HunterModel::where('id', $id)->update($validations); return redirect('/'); }
也可以使用路由模型绑定简化代码:
public function update(HunterRequest $request, HunterModel $hunter) { $validations = $request->validated(); $validations['properties'] = $validations; $hunter->update($validations); return redirect('/'); }
额外说明
- 模型配置
'properties' => 'array'后,从数据库取出该字段时,Laravel会自动将JSON转为PHP数组,无需手动解码。 - 若希望
properties只包含其他字段(排除自身),可添加以下代码:
$validations['properties'] = $validations; unset($validations['properties']);
内容的提问来源于stack exchange,提问作者user20509677
相关产品推荐
相关产品推荐

