How do I correctly hide model relationships from returning in toArray() or toJson()?

前端 未结 2 580
感情败类
感情败类 2021-01-15 15:07

I\'m currently working on a project where I\'m writing an API, and with a lot of the models, I\'m trying to hide their parent relationships from being returned, like so

相关标签:
2条回答
  • 2021-01-15 15:17
    protected $hidden = array(
            'id', 'user_id', 'user'
                               ^^^ relationship's method name which is "user"
    );
    

    if you want to hide the relationship , you have to include method name under hidden attributes. From your hidden attributes, i can see, you are perfectly hiding user relationship from Array and JSON conversion . However, if you have 'user' column in your users_tokens table, I have no idea what Laravel will behave.

    public function user() {
        return $this->belongsTo('User');
    }
    
    0 讨论(0)
  • 2021-01-15 15:39

    I faced same question and decided to clarify this with PR to Laravel docs. Seems like there is no difference and that note was incorrect.

    https://github.com/laravel/docs/pull/3351

    0 讨论(0)
提交回复
热议问题