Laravel接口如何仅在指定端点隐藏file字段且保留file_size
解决方法
你只需要在ReportResource中控制字段返回即可,同时注意不能从Eloquent查询里移除file字段(因为访问器依赖这个字段的值计算file_size),具体有两种简单方式:
方式1:直接移除Resource中的file字段定义
直接删掉toArray方法里的'file' => $this->whenNotNull($this->file),这一行,这样接口就不会返回file字段,但查询时已经获取到的file值依然能被访问器用来计算file_size。
修改后的ReportResource代码:
public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'year' => $this->year, 'views' => $this->whenNotNull($this->views), 'file_size' => $this->fileSize, // 保留该字段 'created_at' => $this->created_at, 'company' => new CompanyResource($this->company), ]; }
方式2:用Resource的$hidden属性批量隐藏
如果想更明确地控制字段隐藏,可以在ReportResource类中添加$hidden属性,指定要隐藏的字段:
class ReportResource extends JsonResource { protected $hidden = ['file']; public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'year' => $this->year, 'views' => $this->whenNotNull($this->views), 'file_size' => $this->fileSize, 'created_at' => $this->created_at, 'company' => new CompanyResource($this->company), ]; } }
这种方式下,即便你不小心在toArray里写了file字段,它也会被自动隐藏,适合需要批量管理隐藏字段的场景。
关键提醒
无论用哪种方式,Eloquent查询里必须保留file字段的选择,因为模型的getFileSizeAttribute访问器依赖$this->attributes['file']的值,如果查询没包含该字段,会导致Storage::size()调用时找不到文件路径,引发错误。
内容的提问来源于stack exchange,提问作者d3ridi
相关产品推荐
相关产品推荐

