在为变量分配ID时,尝试在Laravel中获取非对象错误的属性

问题描述:

  1. I'm getting the row in the following code :
$grpusrow = DB::table('grpusrs') 
                       ->where('group_id', $id)
                      ->where('user_id', $u_id)
                      ->get();
  1. And then getting the ID in this line :
$grpusrid = $grpusrow->id;
  1. I receive the following error on the line in number 2 :

Trying to get property of non-object

->get() will always return multiple objects at once. You're simply not telling it which index of $grpusrow to get the ID from.

$grpusrows = DB::table('grpusrs') 
                    ->where('group_id', $id)
                    ->where('user_id', $u_id)
                    ->get();

foreach ($grpusrows as $grpusrow) {
    dump($grpusrow->id);
}

// Or

$grpusrow = DB::table('grpusrs') 
                    ->where('group_id', $id)
                    ->where('user_id', $u_id)
                    ->first();

dump($grpusrow->id);

Maybe 2 solutions:

  1. If you want a unique row in return (with a primary key in arguments for example), you should try ->first() instead of ->get().

  2. The problem is the using of where clauses, I think it works with array when you want more than one where clause, try like this :

->where([['group_id', '=', $id],['user_id', '=', $u_id]])->get(); ( or first() )