Laravel 5 调用未定义的方法stdClass::Laravel 5.3
当我在blade中调用我的方法时,出现了这个错误 我的模型Laravel 5 调用未定义的方法stdClass::Laravel 5.3,laravel-5,Laravel 5,当我在blade中调用我的方法时,出现了这个错误 我的模型 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)){
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
@foreach($users作为$user)
{{$user->hasRole(“Admin”)}
{{csrf_field()}}
{{$user->name}
{{$user->email}
亚西纳
@endforeach
但是我得到了:
“4ec2afb0bd7b9558404eeeb89a6d9200e0c5639a.php第18行中的FatalErrorException:
调用未定义的方法stdClass::hasRole()
我不明白为什么 感谢世邦魏理仕的帮助,我找到了问题所在。 是我使用query builder让我的用户将其传递给我的视图,现在我使用的是雄辩的模型,一切正常 解决方案: 在我的控制器类中:
//$users = DB::table('users')->get();//Query Builder
$users = User::all();//Eloquent
return view('admin.home', compact("users"));
感谢您的帮助,因为
$users
中的元素显然不是User
类的实例,而是StdClass
的实例。非常感谢您的快速回答!这是我的第一个项目whit laravel,我知道有一种简单的方法可以获得我的用户实例?谢谢