Search code examples
phplaraveleloquentpivot-table

Hide specific columns from pivot key


I have 2 tables say abc and xyz with ManyToMany relationship built over another table say abc_xyz (whose data will be returned as pivot key). However, pivot key upon retrieval has abc_id and xyz_id in return. I am able to access other columns in from abc_xyz table using method withPivot('dummy')

But, I want to hide the abc_id and xyz_id from the response. How do I do that? I can hide the entire pivot key by using $hidden array but I want to hide only specific columns not the entire key.

Current Response

{
   "abc_uuid": "some uuid",
   "xyz" : [
       {
           "xyz_uuid": "some uuid",
           "pivot": {
                "abc_id": 1,
                "xyz_id": 1,
                "dummy" : "dummy value"
            }
       },
       {
           "xyz_uuid": "some uuid",
           "pivot": {
                "abc_id": 1,
                "xyz_id": 2,
                "dummy" : "dummy value"
            }
       }
   ]
}

So, I need only dummy from the pivot key, and hide abc_id and xyz_id. How do I do that?


Solution

  • Found a crude way to get this done. Found this answer in laravel issues unable to find the link now. However, it asks me to just add a method in my model and unset the keys I do not want.

    public function toArray()
    {
        $attributes = $this->attributesToArray();
        $attributes = array_merge($attributes, $this->relationsToArray());
        foreach($attributes['xyz'] as $key => $value) {
            unset($value['pivot']['abc_id']);
            unset($value['pivot']['xyz_id']);
            $attributes['xyz'][$key] = $value;
        }
        return $attributes;
    }
    

    this unsets the unwanted keys from my response. I hope laravel gives out an easy way for this.