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

->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']);
});

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');
    }
...
}

Tags:

Laravel