AHeavyObject
AHeavyObject

Reputation: 602

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

I use in my model code to get a relation

class User extends Authenticatable
{
    // ...
    public function extensions()
    {
        return $this->belongsToMany(Extension::class, 'v_extension_users', 'user_uuid', 'extension_uuid');
    }
    // ...
}

The Extension has field password hidden.

class Extension extends Model
{
    // ...
    protected $hidden = [
        'password',
    ];
    // ...
}

Under some circumstances I want to makeVisible the password field.

How can I achieve this?

Upvotes: 7

Views: 23349

Answers (4)

DevK
DevK

Reputation: 9942

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

Upvotes: 15

Midhun S
Midhun S

Reputation: 11

This is working for me

$user=User::select(['id','password as user_password'])->first();

Upvotes: -1

Thom Seddon
Thom Seddon

Reputation: 1475

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

Upvotes: 0

AHeavyObject
AHeavyObject

Reputation: 602

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

Upvotes: 2

Related Questions