Framework: Allow users to hide attributes of relationship in Eloquent

Created on 30 May 2015  路  1Comment  路  Source: laravel/framework

I'd like to be able to hide or make visible only certain attributes of a relationship. This is similar to #373, allowing users to hide an entire relationship, but with relationship attributes.

class User extends Model {

  protected $hidden = ['password', 'email'];

}
class Project extends Model {

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

}

I want to hide the password and email when accessing User through Project. But when accessing User directly, I don't want to hide email. $hidden hides attributes for the entire model no matter through what relationship the model is accessed. Is there another way of doing this that I'm missing?

A possible syntax for this might be to use dot notation in the $hidden property to target the attribute that you want to hide in the relationship.

class Project extends Model {

  protected $hidden = ['user.password', 'user.email'];

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

}

Most helpful comment

I figured out how to do what I wanted

class Project extends Model {

  public function user()
  {
      return $this->belongsTo('App\User')->select(array('id', 'username'));
  }

}

So that I'm only selecting the attributes that I want in this relationship

Edit: I also had to select the id in order for the relationship to still work

>All comments

I figured out how to do what I wanted

class Project extends Model {

  public function user()
  {
      return $this->belongsTo('App\User')->select(array('id', 'username'));
  }

}

So that I'm only selecting the attributes that I want in this relationship

Edit: I also had to select the id in order for the relationship to still work

Was this page helpful?
0 / 5 - 0 ratings