使用PageManager向Backpack假列extras上传图片失败问题
问题描述
在Backpack框架中尝试将图片上传至extras假列时,模型的setImageAttribute方法接收到的$value为空,导致图片无法完成上传。若将image设为真实数据库列,mutator能正常接收值并完成上传,但只为单一页面类型新增数据库列并不合理。已排除mutator方法名称错误的问题。
相关代码如下:
PageTemplates.php
$this->crud->addField([ 'name' => 'image', 'label' => 'Image', 'type' => 'upload', 'upload' => true, 'disk' => 'public', 'store_in' => 'extras', 'fake' => true ]);
Page.php 模型
protected $table = 'pages'; protected $primaryKey = 'id'; public $timestamps = true; protected $fillable = ['template', 'name', 'title', 'slug', 'content', 'extras']; protected $fakeColumns = ['extras']; protected $casts = ['extras' => 'array']; // ... public function setImageAttribute($value) { $attribute_name = "image"; $disk = "public"; $destination_path = "/images/pages"; $this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path); }
解决方案
当使用Backpack的fake字段并指定store_in时,上传的文件值会被Backpack自动合并到store_in指向的数组字段(即extras)中,不会作为单独属性传递给对应的setXxxAttribute方法,因此setImageAttribute无法接收到上传值。
可以通过重写setExtrasAttribute方法来处理图片上传逻辑,具体步骤:
- 从传入的
extras数组中提取image字段的上传值; - 调用Backpack的
uploadFileToDisk方法完成图片上传,获取存储路径; - 将上传后的路径更新回
extras数组; - 处理后的数组最终存入数据库。
修改后的Page.php模型代码:
protected $table = 'pages'; protected $primaryKey = 'id'; public $timestamps = true; protected $fillable = ['template', 'name', 'title', 'slug', 'content', 'extras']; protected $fakeColumns = ['extras']; protected $casts = ['extras' => 'array']; // ... public function setExtrasAttribute($value) { // 检查是否存在待上传的图片 if (isset($value['image']) && $value['image']) { $attribute_name = "image"; $disk = "public"; $destination_path = "/images/pages"; // 执行上传并获取路径 $uploaded_path = $this->uploadFileToDisk($value['image'], $attribute_name, $disk, $destination_path); // 更新extras数组中的image值 $value['image'] = $uploaded_path; } // 将处理后的数组存入数据库 $this->attributes['extras'] = json_encode($value); }
注意:需要移除原来的setImageAttribute方法,因为上传逻辑已合并到setExtrasAttribute中。
这样处理后,表单提交时Backpack会将image字段的值放入extras数组,模型的setExtrasAttribute会自动处理图片上传,并将最终路径保存到extras字段中。
内容的提问来源于stack exchange,提问作者Ben Faulkner
相关产品推荐
相关产品推荐

