在播种机中调用未定义的方法,Laravel

Call to undefined method in seeder, Laravel

我尝试为用户创建角色和权限,但当我尝试为角色分配权限时在播种机上出现错误。

//from seeder
    use App\Ability;
    use App\Role;
    use App\User;

    public function run(){
        $owner = Ability::where('name', '=', 'owner');
        $administrator = Role::where('name', '=', 'administrator');
        $administrator->allowTo($owner);
    }

//from my Role Model
     public function abilities()
     {
         return $this->belongsToMany(Ability::class)->withTimestamps();
     }

     public function allowTo($ability)
     {
         $this->abilities()->save($ability);
     }

Call to undefined method Illuminate\Database\Eloquent\Builder::allowTo()

您没有获取数据,您只是在检查条件。

试试这个,如果对你有帮助请告诉我

//from seeder
    use App\Ability;
    use App\Role;
    use App\User;

    public function run(){
        $owner = Ability::where('name', '=', 'owner')->first();
        $administrator = Role::where('name', '=', 'administrator')->first();
        $administrator->allowTo($owner);
    }

//from my Role Model
     public function abilities()
     {
         return $this->belongsToMany(Ability::class)->withTimestamps();
     }

     public function allowTo($ability)
     {
         $this->abilities()->save($ability);
     }