Entrust with Laravel - Eloquent queries with conditional roles

354 Views Asked by At

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.

1

There are 1 best solutions below

1
On BEST ANSWER

This is how I managed to make it work. However I'm not able to get the Relation object instead I'm getting collection of Users having role Admin

public function admin(){

    return $this->hasOne('App\User')->get()->map(function($u){

        if($u->hasRole('admin') && $u != null){

            return $u;

        }

    })->reject(function ($u){
        return $u == null;
    });


}