I'm having single User eloquent model in my Laravel App:
I'll be using Entrust for roles. Users can have multiple roles.
I already managed to get the User have multiple roles with same eloquent model User like this:
public function company(){
if($this->hasRole('admin')){
return $this->hasOne('App\Company');
}elseif($this->hasRole('member')){
return $this->belongsTo('App\Company');
}
}
How to handle this in other models suppose in Company model:
public function admin(){
$this->hasOne('App\User'); //if has role admin
}
public function members(){
$this->hasMany('App\User'); //if has role member
}
How to get this working?
Edit I'm able to traverse through the users and get the related users with specific role but it adds null items in the collection:
public function admin(){
return $this->hasOne('App\User')->get()->map(function($u){
if($u->hasRole('admin') && $u != null){
return $u;
}
});
}
Though, I'm checking the $u != null
I can see many null objects in the collection.