调用 Laravel 中未定义的方法 App\User::role()

Lit*_*ito 1 roles laravel

我想创建一个具有特定角色的用户列表(如果给出多个角色,则为角色)

在我的用户控制器中

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')); 
Run Code Online (Sandbox Code Playgroud)

但我有这个错误

在此处输入图片说明

如果我 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');
    }
Run Code Online (Sandbox Code Playgroud)

用户/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     
Run Code Online (Sandbox Code Playgroud)

更改@foreach($users->role as $item)@foreach($user->roles as $item)给我“此集合实例上不存在属性 [角色]”

用户表迁移

在此处输入图片说明

角色和权限表迁移

在此处输入图片说明

回答

来自Simon Morris的回答。

@foreach($users as $user)
    {{ $user->name }}
    @foreach ($user->roles as $role)
        {{ $role->name }}
    @endforeach
@endforeach
Run Code Online (Sandbox Code Playgroud)

我从这里的一些建议中删除了我添加的基础关系。并实施我上面粘贴的答案。

如果用户赋予多个角色,该代码会显示用户列表及其特定的用户角色。

谢谢你们的回答!干杯!

Sim*_*ris 5

你正在打电话$user->role()而不是$user->roles()

将它们作为数组循环遍历你需要做的

foreach($user->roles as $role){
  // do something with role here
}
Run Code Online (Sandbox Code Playgroud)