当我试图检查用户是否在数据库中有角色时,我遇到了问题。当我在模型外做时,它工作得很好,但由于某种原因,当我需要在模型中做时,我得到"试图获得非对象的属性"错误。下面是我的代码:
public function owed_amount() {
$user_total = $this->total_expenses();
$expenses = Expense::where('removed', false)->get();
$total = 0;
foreach ($expenses as $expense) {
$total += $expense->amount;
}
$total_users = 0;
$users = User::get();
foreach ($users as $user) {
if($user->has_role('is-payee')) //Error comes from here!
{
$total_users++;
}
}
$paid_in = $this->total_paid_in();
$got_paid = $this->total_got_paid();
$owed = $user_total - $total/$total_users + $paid_in - $got_paid;
return number_format($owed, 2);
}
public function has_role($data) { //Checking for role in database
$perm = Permission::where('data', $data)->first();
$ptg = PermissionToGroup::where([
'group_id' => $this->usergroup->id,
'perm_id' => $perm->id
])->first();
if($ptg===NULL){ return false; }
else{ return true; }
}
谢谢你的帮助!
您必须检查是否有$perm
的结果 public function has_role($data) { //Checking for role in database
$perm = Permission::where('data', $data)->first();
if($perm) {
$ptg = PermissionToGroup::where([
'group_id' => $this->usergroup->id,
'perm_id' => $perm->id
])->first();
if($ptg===NULL){ return false; }
else{ return true; }
}
else
return false;
}