Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

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

<?php namespace Viper\Model;

class User_Token extends Eloquent {

    protected $table = 'users_tokens';

    protected $fillable = array(
        'user_id', 'token'
    );

    protected $hidden = array(
        'id', 'user_id', 'user'
    );

    public function user() {
        return $this->belongsTo('User');
    }

}

In the Laravel documentation, for the Eloquent > Converting to Array or Json section, it clearly says

Note: When hiding relationships, use the relationship's method name, not the dynamic accessor name.

What exactly does this mean? In the above example, both the method name and the dynamic accessor name are the same, and I can't for the life of me, think of a situation where this wouldn't be the case.

like image 433
ollieread Avatar asked Sep 02 '25 13:09

ollieread


1 Answers

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');
}
like image 198
Anam Avatar answered Sep 05 '25 07:09

Anam