php - 对 voyager 隐藏字段
问题描述
我想让一些字段从 json 响应中隐藏。我使用了 Voyager 多语言功能。所以我的回复如下所示:
$collection = Diet::all()->makeHidden(['description'])->translate(app()->getLocale(), 'en');
return response()->json($collection);
但是响应中包含描述字段。没有->translate(app()->getLocale(), 'en')
. 如何隐藏描述字段?
解决方案
为了隐藏这些字段,我创建了 JsonResource,如下所示:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class DietCollection extends JsonResource
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
//here we return only required fields
return [
'id' => $this->id,
'title' => $this->title,
'image' => $this->image,
];
}
}
并像这样使用它:
$collection = Diet::all()->translate(app()->getLocale(), 'en');
return response()->json(DietCollection::collection($collection));
推荐阅读
- ansible - 在剧本中使用命令任务时在 Ansible 中出现内存错误
- python - How to create list of dictionaries from a single dictionary?
- excel - 如何以用户形式将数据传输到同一工作簿中的不同工作表(使用 ComboBox1)?
- excel - 删除行(向后工作),但使用范围变量?
- node.js - Mongo 和 Node.js 查找和聚合
- python - 将日历日期转换为朱利安日期 - python
- c - while (fgets (buffer, 1024, fp) != NULL) in while (fgets (buffer, 1024, fp) != NULL)
- node.js - MongoDB中的日期操作和比较
- wordpress - React/Gatsby/Wordpress 卡在“源和转换节点”上
- ios - 使用 CTCellularPlanProvisioningRequest 获取 iccid