Search code examples
phplaravelvoyager

Hide fields from voyager Translatable


I want to make some fields hidden from json response. I have used Voyager multilingual feature. So my response looks like below:

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

But description field included to the response. It works perfect without ->translate(app()->getLocale(), 'en'). How I can hide description field?


Solution

  • To hide these fields I've created JsonResource like below:

    <?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,
            ];
        }
    }
    

    And used it like this:

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