首页 > 解决方案 > 对 voyager 隐藏字段

问题描述

我想让一些字段从 json 响应中隐藏。我使用了 Voyager 多语言功能。所以我的回复如下所示:

$collection = Diet::all()->makeHidden(['description'])->translate(app()->getLocale(), 'en');
return response()->json($collection);

但是响应中包含描述字段。没有->translate(app()->getLocale(), 'en'). 如何隐藏描述字段?

标签: phplaravelvoyager

解决方案


为了隐藏这些字段,我创建了 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));

推荐阅读