php - Laravel object_get -
i have base user model object. each user can either staff member, parent or student. each account type has associated model.
for example:
class user extends model {      public function details()     {         switch($this->account_type) {             case 'staff':    return $this->hasone(staff::class);             case 'student':  return $this->hasone(student::class);             case 'parent':   return $this->hasone(parentuser::class);         }          return null;     } if run:
 echo $user->details->staff_code; then outputs crs example. however, if run object_get():
object_get($user, 'details.staff_code'); then outputs null.
i figured because in object_get() method, has line:
if (! is_object($object) || ! isset($object->{$segment})) i assume because details property magic/dynamic laravel model property, isset() doesn't work on it. 
whats best way handle this? safe edit object_get() method , replace isset() segment more robust? don't want edit source code in vendor directory.
should create own object_get helper function, , if so, should place / autoload it?
is there method of achieving result want i'm unaware of?
any appreciated.
well, seems bit hacky, seems work, , need on 1 user model.
i've taken magic __isset() method illuminate\database\eloquent\model class, , overrode in user class.
i've added method_exists check in __isset() method check see if relationship method exists. because if relationship method exists, @ least know dynamic variable same method name exists.
this __isset() method in model if else needs it:
public function __isset($key) {     return (                 isset($this->attributes[$key]) ||                  isset($this->relations[$key]) ||                  method_exists(static::class, $key)            ) ||            ($this->hasgetmutator($key) && ! is_null($this->getattributevalue($key))); } now, if run:
object_get($user, 'details.staff_code') it returns correct value, instead of default null.
Comments
Post a Comment