1

I am trying to add a custom attribute "role" to my User model. My current implementation is like this:

User extends Authenticatable
{
   protected $appends = array('role');

   public $getRoleAttribute()
   {
     $role = DB::table('acl_user_has_roles')->where('user_id', $this->id)
               ->value('role');
     return $role;
   }
}

This implementation largely works. The concern is, this role attribute is referenced many times in the life time of $user instance. Whenever it is reference, the getRoleAttribute() function will be called, then database queries will be executed. It seems a bit unnecessary to me, so I am trying find a way to only run these queries once, preferably when model instance is contructed:

I tried to override model constructor as described in answer to another similar question:

public $role;

public function __construct(array $attributes = array())
{
    parent::__construct($attributes);

    $this->role= $this->role();
}

protected function role()
{
  $role = DB::table('acl_user_has_roles')->where('user_id', $this->id)
               ->value('role');
  return $role;
}

When I tried to reference the role attribute like this:

$user = User::find(1);
echo $user->role;

I get nothing.

if I simply set the role attribute to some dummy text:

$this->role = "Dummy Role";

instead of:

$this->role();

Then I can get this "Dummy Role" text.

What am I missing here?

Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
Zhiyong Li
  • 469
  • 3
  • 14

0 Answers0