I'm using Laravel 5.4
, Laravel Roles
from here and Eloquent
relationships.
I'm trying to retrieve the users of a company along with their roles.
User::find(1)->roles
gets me the user's roles whose id =1
Company::find(1)->users
gets me all the users that belongs to the company whose id =1
(without the roles of users).
Company::find(1)->users->roles
returns an error Property [roles] does not exist on this collection instance.
Questions
- Is it possible to do what I want to do ?
- If so, how should I do it ?
User.php
class User extends Authenticatable
{
use HasRoleAndPermission;
public function company()
{
return $this->belongsTo('App\Company');
}
public function user()
{
return $this->belongsTo(User::class);
}
}
HasRoleAndPermission.php
trait HasRoleAndPermission
{
public function roles()
{
return $this->belongsToMany(config('roles.models.role'));
}
}
Company.php
class Company extends Model
{
public function users() {
return $this->hasMany('App\User');
}
}