请参阅下面的 AdministrationController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Foundation\Auth\User;
class AdministrationController extends Controller
{
public function index() {
$user = User::find(1);
$role = Role::where('name', 'owner')->get()->first();
$user->assignRole($role);
}
}
这是我的用户模型的重要部分:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasRoles;
use Notifiable;
...
}
奇怪的是,$user->assignRole($role);
AdministrationController.php 中的行会引发以下错误:
BadMethodCallException
Method Illuminate\Database\Query\Builder::assignRole does not exist.
但是,在 Tinker 中,此命令序列可以正常工作并产生所需的结果:
>>> $user=User::find(1)
>>> $role=Spatie\Permission\Models\Role::where('name', 'owner')->get()->first()
>>> $user->assignRole($role)
我搜索了这个问题,尝试了一些修复建议,但没有任何帮助。我的 AdministrationController.php / User.php 有什么问题?