我想创建一个具有特定角色的用户列表(如果给定了多个角色,则为角色)
在我的用户 Controller 中
use DB;
use Auth;
use Storage;
use App\Role;
use App\HasRoles;
use App\User;
use App\Profile;
$users = User::with('roles')->where('name', 'admin')->get();
return view('dashboard.users.index', compact('users'));
但是我有这个错误
如果我 dd($users);
我可以看到角色在那里
我该如何解决这个问题?谢谢!
编辑:用户模型
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, HasRoles;
protected $fillable = [
'name', 'email', 'phone_number', 'avatar', 'password', 'verification_code'
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
'phone_verified_at' => 'datetime',
];
public function profile()
{
return $this->hasOne('App\Profile', 'user_id','id');
}
public function mailingAdd()
{
return $this->hasOne('App\MailingAddress', 'user_id','id');
}
用户/index.php
@foreach($users->role as $item)
<tr>
<td>{{ $loop->iteration }}</td>
<td><a href="{{ url('/dashboard/users', $item->id) }}">{{ $item->name }}</a></td>
<td>{{ $item->email }}</td>
<td>{{ $item->role()->name }}</td>
<td>{{ $item->phone_number==null ? 'None' : $item->phone_number }}</td>
<td>
@if($item->phone_verfied_at==null)
<span class="badge badge-danger">not yet verified</span>
@else
<span class="badge badge-success">verified</span>
@endif
</td>
</tr>
@endforeach
将 @foreach($users->role as $item)
更改为 @foreach($user->roles as $item)
给我“Property [roles]此集合实例上不存在”
用户表迁移
角色和权限表迁移
回答
根据 Simon Morris 的回答。
@foreach($users as $user)
{{ $user->name }}
@foreach ($user->roles as $role)
{{ $role->name }}
@endforeach
@endforeach
我从这里的一些建议中删除了我添加的关系。并实现我在上面粘贴的答案。
如果用户被赋予多个角色,该代码会显示带有特定用户角色的用户列表。
谢谢大家的回答!干杯!
最佳答案
您正在调用 $user->role()
而不是 $user->roles()
要将它们作为一个数组来循环,你需要做
foreach($user->roles as $role){
// do something with role here
}
关于laravel - 在 Laravel 中调用未定义的方法 App\User::role(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905292/