cviebrock / eloquent-taggable

Easily add the ability to tag your Eloquent models in Laravel.
MIT License
537 stars 72 forks source link

Hide fields in JSON response #68

Closed pierrocknroll closed 5 years ago

pierrocknroll commented 6 years ago

Hi, Thanks a lot for your great package !

My Laravel is an API, and I want to return the tags associated with my Model so I've made :

protected $with = ['tags'];

in my Model.

So a response from my API looks like :

{
    "id": 1,
    "name": "Jacky",
    "tags": [
        {
            "tag_id": 166,
            "name": "TUTU",
            "normalized": "tutu",
            "created_at": "2018-01-24 10:33:13",
            "updated_at": "2018-01-24 10:33:13",
            "pivot": {
                "taggable_id": 1,
                "tag_id": 166,
                "created_at": "2018-01-24 10:40:46",
                "updated_at": "2018-01-24 10:40:46"
            }
        }
    ],
}

But I want to hide the created_at, updated_at and pivot fields, is it possible without modifying your package ? Thanks !

cviebrock commented 6 years ago

Probably the "right" way to do this is to use Eloquent Resources if you are running Laravel 5.5, or something like Fractal if you aren't.

In order to do it "natively", you'd need to extend the package's Tag class and add a toJson() method on it. The current version of the package doesn't make this easy, but it's on my to-do list for the next major version (although there is no ETA for that right now).

cviebrock commented 6 years ago

(Leaving this open as a reminder for me.)

pierrocknroll commented 6 years ago

Thanks for the answer ! For now I've made something like this in my Model :

    public function toArray()
    {
        $array = parent::toArray();
        if (isset($array['tags'])) {
            foreach ($array['tags'] as &$tag) {
                unset($tag['created_at'], $tag['updated_at'], $tag['pivot']);
            }
        }
        return $array;
    }

Not very pretty but I can live with it.

cviebrock commented 5 years ago

Just looking over old issues ... I said:

In order to do it "natively", you'd need to extend the package's Tag class and add a toJson() method on it.

The package does allow you to change the Tag class to your own implementation, so this should be trivial to do now. I don't know why I mention this at the time I made that change, but I'm closing the issue now since it should be doable.