Search code examples
laravellaravel-collectionlaravel-api

hide attributes in Laravel API Resource


I want to hide an attribute in the Collection API Resource I don't want to do it always, so I need something like makeHidden() to do it when I want.

But API Resource return Illuminate\Support\Collection instance that has not makeHidden() method the Eloquent Collection Class is Illuminate\Database\Eloquent\Collection

how can I do that ?


Solution

  • If you want to customize a response for some case, you could create a second Resource class that will only contain your desired attributes:

    class FirstResource extends JsonResource {
    
        public function toArray($request)
        {
            return [
                'first_value' => $this->first_value,
                'second_value' => $this->second_value,
                'third_value' => $this->third_value,
                'fourth_value' => $this->fourth_value,
            ];
        }
    }
    
    class SecondResource extends JsonResource {
    
        public function toArray($request)
        {
            return [
                'first_value' => $this->first_value,
                'second_value' => $this->second_value,
            ];
        }
    }
    

    Then use them whenever you need one of them:

    public function aControllerMethod()
    {
        $model = MyModel::find($id);
    
        return new FirstResource($model);
    }
    
    public function anotherControllerMethod()
    {
        $model = MyModel::find($id);
    
        return new SecondResource($model);
    }
    

    Now you will have two different responses from the same model (or collection).