Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel/Eloquent - Eager loaded hidden/visible properties

When using Laravel's Eloquent ORM, I can't seem to set the $hidden and $visible properties on my Model dynamically.

Example 1: This works:

class User extends Eloquent {
   $this->visible = array('field_name');

   function read() 
   {
      return User::all();
   }
}

Example 2: Setting the visible property on the Eloquent Class dynamically, doesn't work:

class User extends Eloquent {
   function read($visible = array('field_name'))
   {
      $this->visible = $visible; // Also tried: $this->setVisible($visible);

      return User::all();
   }
}

Example 3: Solution that works on the Model itself, but not on eagerly loaded Models:

class User extends Eloquent {
   function read($visible = array('field_name'))
   {
      $users = User::all();

      return $users->get()->each(function($row) use ($visible) {
         $row->setVisible($visible);
      });
   }
}

In order to set the $visible property dynamically on Eagerly Loaded Models, I don't see another solution than to get Example 2 to work. But how?

like image 747
Ronald Hulshof Avatar asked Jun 04 '13 11:06

Ronald Hulshof


1 Answers

As $visible is set on an instance level (i.e. it's not a static variable shared between all models of the same type), no - there's no better way to do this.

like image 139
Andreas Avatar answered Oct 16 '22 04:10

Andreas