2016-09-18 130 views
1

我在嘗試檢查用戶是否在數據庫中有角色時遇到問題。當我在模型外部執行時,它工作正常,但由於某種原因,當我需要在模型中執行此操作時,我得到「嘗試獲取非對象的屬性」錯誤。這裏是我的代碼:試圖獲取非對象的屬性。 Laravel 5.2

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; } 
    } 

爲您的幫助歡​​呼!

+0

結果,如果有什麼是$燙髮沒有結果=權限::在哪裏(「數據」,$數據) - >第一(); –

+0

我認爲,但我加倍檢查數據庫,它肯定存在 – Imphusius

+0

你可以提供有關錯誤的更多信息?,我發佈了一個解決方案,我認爲你的代碼錯誤 –

回答

2

你必須檢查是否有用於燙髮$

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; 
    } 
相關問題