Laravel - how to makeVisible an attribute in a Laravel relation?

后端 未结 3 1589
时光说笑
时光说笑 2020-12-18 05:04

I use in my model code to get a relation

class User extends Authenticatable
{
    // ...
    public function extensions()
    {
        return $this->belo         


        
相关标签:
3条回答
  • 2020-12-18 05:12

    Well, I got the idea from https://stackoverflow.com/a/38297876/518704

    Since my relation model Extension::class is called by name in my code return $this->belongsToMany(Extension::class,... I cannot even pass parameter to it's constructor.

    So to pass something to the constructor I may use static class variables.

    So in my Extension model I add static variables and run makeVisible method. Later I destruct the variables to be sure next calls and instances use default model settings.

    I moved this to a trait, but here I show at my model example.

    class Extension extends Model
    {
        public static $staticMakeVisible;
    
        public function __construct($attributes = array())
        {
          parent::__construct($attributes);
    
          if (isset(self::$staticMakeVisible)){
              $this->makeVisible(self::$staticMakeVisible);
          }
       }
    .....
    
        public function __destruct()
        {
          self::$staticMakeVisible = null;
        }
    
    }
    

    And in my relation I use something like this

    class User extends Authenticatable
    {
    ...
        public function extensions()
        {
            $class = Extension::class;
            $class::$staticMakeVisible = ['password'];
    
            return $this->belongsToMany(Extension::class, 'v_extension_users', 'user_uuid', 'extension_uuid');
        }
    ...
    }
    
    0 讨论(0)
  • 2020-12-18 05:15

    The highest voted answer didn't seem to work for me (the relations attribute seems to be a protected array now so can't be used as a collection in @DevK's answer), I instead used:

    $parent->setRelation('child', $parent->child->first()->setVisible(['id']));
    
    0 讨论(0)
  • 2020-12-18 05:27

    ->makeVisible([...]) should work:

    $model = \Model::first();
    $model->makeVisible(['password']);
    
    $models = \Model::get();
    $models = $models->each(function ($i, $k) {
        $i->makeVisible(['password']);
    });
    
    // belongs to many / has many
    $related = $parent->relation->each(function ($i, $k) {
        $i->makeVisible(['password']);
    });
    
    // belongs to many / has many - with loading
    $related = $parent->relation()->get()->each(function ($i, $k) {
        $i->makeVisible(['password']);
    });
    
    0 讨论(0)
提交回复
热议问题