Search code examples
phplaravellaravel-5

Hiding pivot attribute


I know you can hide an entire pivot table as such

protected $hidden = ['pivot'];

How do you hide a specific field within pivot table, like

protected $hidden = ['pivot.created_at'];

The above does not work from what I've tested


Solution

  • After so much trying and looking into source of Laravel Model, i finally got it achieved.

    Please put following method at your Model.

    /**
     * Convert the model instance to an array.
     *
     * @return array
     */
    public function toArray()
    {
        $attributes = $this->attributesToArray();
        $attributes = array_merge($attributes, $this->relationsToArray());
        unset($attributes['pivot']['created_at']);
        return $attributes;
    }
    

    This solves the purpose.