Reputation: 678
I have problem when I'm trying to check if user has role in database. When I do it outside the model it works fine but for some reason when I need to do it in model I get "Trying to get property of non-object" error. Here is my code:
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; }
}
Cheers for your help!
Upvotes: 1
Views: 665
Reputation: 1168
You have to check if there is a result for $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;
}
Upvotes: 2