Laravel当我尝试访问类中的函数时调用未定义的方法

时间:2017-12-21 07:36:38

标签: laravel laravel-5

在laravel上实现ACL之后我想使用sync向用户附加一些权限,当我尝试使用此代码时:

Route::get('/setPermission', function () {
    //auth()->loginUsingId(1);

    return \App\Role::whereName('admin')->permissions()->sync(
        [
            1, 2
        ]
    );
});

我收到此错误:

"Call to undefined method Illuminate\Database\Query\Builder::permissions()"

我的Role课程:

class Role extends Model{
    protected $fillable = ['name','label'];

    public function users(){
        return $this->belongsToMany(User::class);
    }

    public function permissions(){
        return $this->belongsToMany(Permission::class);
    }
}

Permission上课:

class Permission extends Model{
    protected $fillable = ['name','label'];

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

用户获取Roles的结果:

[{"id":2,"name":"admin","label":"\u0645\u062f\u06cc\u0631 \u06a9\u0644 \u0633\u0627\u06cc\u062a \u0648 \u0633\u06cc\u0633\u062a\u0645","created_at":"2017-12-21 07:44:09","updated_at":"2017-12-21 07:44:09"}]

1 个答案:

答案 0 :(得分:0)

此代码解决了问题:

->first()

之后添加whereName
Route::get('/setPermission', function () {
    //auth()->loginUsingId(1);

    return \App\Role::whereName('admin')->first()->permissions()->sync(
        [
            1, 2
        ]
    );
});