how to remove laravel_through_key in my hasManyThrough relation in Laravel

Viewed 2619

I have a hasManythrough relation. As following:

public function contacts(){
    return $this->hasManyThrough(ContactContent::class, Content::class,"id",'as_parent_content_id','as_parent_content_id','id');
}
public function getSupportElementsAttribute(){
    return [
        "contacts" => $this->contacts,
        "documents" => $this->documents,
        "assignments" => $this->assignments
    ];
}

This return like this:

"contacts": [
                {
                    "id": 66,
                    "as_parent_content_id": 5074,
                    "created_at": "2020-09-30 16:21:11",
                    "updated_at": "2020-09-30 16:21:11",
                    "create_user_id": 1,
                    "laravel_through_key": 5074
                }
            ],

How to remove this laravel_through_key ?

2 Answers

you can add protected property to model

ref link https://laravel.com/docs/8.x/eloquent-serialization#hiding-attributes-from-json

  /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
       'laravel_through_key'
    ];

or you can use makeHidden()

ref link https://laravel.com/docs/8.x/eloquent-collections#method-makeHidden

public function getSupportElementsAttribute(){
    return [
        "contacts" => $this->contacts->makeHidden('laravel_through_key'),
        "documents" => $this->documents,
        "assignments" => $this->assignments
    ];
}

May be you want to hide this column from collection? Then :

$user = User::with('posts')->get();
$user->makeHidden('laravel_through_key');

Now laravel_through_key will be hidden from your collection.

Alternative solution : add laravel_through_key on your model's $hidden attribute, as :

protected $hidden = [
    'laravel_through_key'
];
Related