简体   繁体   中英

Trying to get property of non-object. Laravel 5.2

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM