当我在刀片中调用我的方法时出现此错误.
我的模特
class User extends Authenticatable{
use Notifiable;
public function roles(){
return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
}
public function hasAnyRole(){
if(is_array($roles)){
foreach ($$roles as $role) {
if($this->hasRole($role)){
return true;
}
}
}else{
if($this->hasRole($roles)){
return true;
}
}
return false;
}
public function hasRole($role){
if($this->roles()->where("name", $role)->first())
return true;
else
return false;
}}
然后在我的home.blade.php
@foreach($users as $user)
{{ $user->hasRole("Admin") }}
<tr>
<form action="{{ route("admin.assignrole") }}" method="get" accept-charset="utf-8">
{{ csrf_field() }}
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td><input type="checkbox" name="admin" value="admin"></td>
<td><input type="checkbox" name="cultura" value="cultura"></td>
<td><input type="checkbox" name="opinion" value="opinion"></td>
<td><button type="button" class="btn btn-primary">Asignar</button></td>
</form>
</tr>
@endforeach
但我得到:
“4ec2afb0bd7b9558404eeeb89a6d9200e0c5639a.php第18行中的FatalErrorException:
调用未定义的方法stdClass :: hasRole()“
我不知道为什么;
最佳答案 感谢CBroe的帮助,我想出了问题所在.
是我使用查询生成器让我的用户将它传递给我的视图,现在我使用Eloquent模型,所有工作正常
解:
在我的控制器类中:
//$users = DB::table('users')->get();//Query Builder
$users = User::all();//Eloquent
return view('admin.home', compact("users"));
谢谢您的帮助