User
和Permission
模型
用户模型
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
public function tambahPermission($permission){
if(is_string($permission)){
$permission = Permission::where('name', $permission)->first();
}
return $this->permissions()->attach($permission);
}
成功运行此播种机
$userAdmin = App\Models\User::create([
'full_name' => 'Admin Full Name',
'address' => 'JL. Kalij',
'phone' => 0857,
'family_name' => 'Rizky Family Admin',
'family_address' => 'JL. Kandangan',
'family_phone' => 085799996666,
'password' => bcrypt('123456789'),
'email' => 'admin@domain.co.id',
'status' => 'confirmed',
'balance' => 0,
]);
$userAdmin->tambahPermission('index.post');
然后我尝试通过像这样的修补程序为特定用户添加其他权限
$user = App\Models\User::find(3); $user->tambahPermission('create.post');
但是我收到了这个错误
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::tambahPermission()'
已更新
我在修补程序中运行它
>>> $user = App\Models\User::find(3);
=> App\Models\User {#750
id: "3",
email: "admin@kika.co.id",
full_name: "Admin Full Name",
address: "JL. Kalijudan 226 D",
phone: "0",
family_name: "Rizky Family Admin",
family_address: "JL. Kandangan",
family_phone: "0",
idcard: null,
status: "confirmed",
balance: "0",
created_at: "2016-10-25 10:34:40",
updated_at: "2016-10-25 10:34:40",
}
>>> $user->tambahPermission('create.post');
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::tambahPermission()'
用户模型中存在 tambahPermission()
方法。
我的代码出了什么问题? 为什么它成功地在播种机上运行而不是修补?
我想要的是为特定用户添加额外的权限。
任何帮助表示感谢。
答案 0 :(得分:0)
find()返回集合而不是模型,其中create()返回模型实例。
检查create:
的功能时public static function create(array $attributes = [])
{
$model = new static($attributes);
$model->save();
return $model;
}
保存数据后,函数返回实例,而find()返回集合...