Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jay_gorio's avatar

Roles and Permissions not working using ACL

I have three models that are related. First I have User that belongs to a Role. On the other hand, Role has many roles. Role belongs to many permissions and Permissions belongs to many Role. I am using the AuthServiceProvider as suggested by jeffrey way . However, when I'm fetching all the permissions of a User I am having error which is, "Call to a member function getKey() on boolean". Can someone please help me on this. Please refer to the codes below.

User.php

public function role()
{
    return $this->belongsTo('App\Role');
}

public function assignRole($role)
{
    return $this->roles()->save(
        Role::whereName($role)->firstOrFail()
    );
}

public function hasRole($role)
{
    if(is_string($role)){
        return $this->role->contains('name', $role);
    }

    return !! $role->intersect($this->role)->count();

}

Role.php

class Role extends Model
{
    public function users()
    {
        return $this->hasMany('App\User');
    }

    public function permissions()
    {
        return $this->belongsToMany('App\Permission');
    }

    public function givePermissions(Permission $permission)
    {
        return $this->permissions()->save($permission);
    }
}

Permission.php

class Permission extends Model
{
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

AuthServiceProvider

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    //get all permissions
    foreach ($this->getPermissionTo() as $permission ) {

        $gate->define($permission->name, function($user) use ($permission){
            return $user->hasRole($permission->roles);
        });
    }
}

public function getPermissionTo()
{
    return Permission::with('roles')->get();
}

and lastly, heres the user table that has a foreign key of role_id

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('role_id')->unsigned();

        $table->string('id_no')->unique()->index();
        $table->string('u_first_name');
        $table->string('u_middle_name');
        $table->string('u_last_name');
        $table->string('email')->unique();
        $table->string('password');

        $table->rememberToken();
        $table->timestamps();
    });
0 likes
1 reply
jay_gorio's avatar

@JeffreyWay Can you please help me on this. I just followed your lesson on using ACL. However the difference is that Im using User belongs To Role and Role hasMany User. In your lesson you used User belongsToMany Role.

Please or to participate in this conversation.