BadMethodCallException消息'方法保存不存在'。
问题描述:
我不明白为什么我有这个错误,我只是创建了assigneRole和权限,但assignRole不起作用,当我使用它时说同步或保存不存在,我认为它必须是因为WhereName,任何想法?BadMethodCallException消息'方法保存不存在'。
这是我的用户模型:
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function assignRole($role)
{
return $this->roles->save(
Role::whereName($role)->firstOrFail()
);
terminal php artisan tinker
$user = User::latest()->first();
$user->assignRole('editor');
}
答
你有没有尝试添加()来$this->roles
所以要$这个 - >角色()?
$this->roles
回报结果 $this->roles()
回归模型relatioship。
有来自$this->roles
差异,$this->roles()
看到这个帖子Difference between method calls $model->relation(); and $model->relation;
+0
谢谢大家,事情是,我在2年前观看了一段视频,laravel 5.1,而且我刚刚认为代码已过时或刚刚停产,最近他们一直这么做,所以我没有重要的细节。 –
如果是这样的话,那么这个方法public function givePermissionTo($权限许可) { 返回这个 - $>权限() - >保存( $许可); }不应该工作,但它确实。 –
对不起,我严重解释自己看到答案。 – LorenzoBerti
这就是最好的解决方案,谢谢我的朋友。 –