Laravel Nova自定义字段如何将多个输入值保存到模型对应字段
解决方案
你当前的前端fill逻辑已经正确把三个字段的内容提交到后端,缺失的是后端字段类的多属性赋值逻辑,按以下步骤调整即可:
- 调整自定义字段的PHP类逻辑
找到该字段对应的PHP类(通常为src/MapAddress.php),新增纬度/经度属性配置、重写Nova字段的默认填充逻辑:
<?php namespace MichaelPresentCompany\NovaMapAddress; use Laravel\Nova\Fields\Field; use Laravel\Nova\Http\Requests\NovaRequest; class MapAddress extends Field { // 自定义属性存储纬度/经度对应的模型字段名 public $latitudeAttribute; public $longitudeAttribute; /** * 设置纬度对应的模型字段 */ public function latitude(string $attribute) { $this->withMeta(['latitude' => $attribute]); $this->latitudeAttribute = $attribute; return $this; } /** * 设置经度对应的模型字段 */ public function longitude(string $attribute) { $this->withMeta(['longitude' => $attribute]); $this->longitudeAttribute = $attribute; return $this; } /** * 重写填充逻辑,一次性给三个模型字段赋值 */ public function fill(NovaRequest $request, $model) { // 填充主地址字段 parent::fill($request, $model); // 填充纬度字段 if ($this->latitudeAttribute && $request->has($this->latitudeAttribute)) { $model->{$this->latitudeAttribute} = $request->input($this->latitudeAttribute); } // 填充经度字段 if ($this->longitudeAttribute && $request->has($this->longitudeAttribute)) { $model->{$this->longitudeAttribute} = $request->input($this->longitudeAttribute); } } }
- 在Nova Resource中调用字段时配置对应属性
确保字段名和你模型中实际存储的字段一致:
// 示例:模型中存储地址的字段为address,纬度为lat,经度为lng MapAddress::make('收货地址', 'address') ->latitude('lat') ->longitude('lng'),
- 检查模型批量赋值配置
确保三个字段都在模型的$fillable数组中,或者模型配置了$guarded = [],避免被Laravel的批量赋值机制过滤。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

