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

Call to undefined method App\User::role() in 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')); 

但我遇到了这个错误

如果我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');
    }

user/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] does not exist on this collection instance"

用户TABLE迁移

角色和权限TABLE迁移

回答

根据 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
}

从外观上看,我认为您错误地引用了 dashboard.users.index 视图中的关系:如果您有:

$user->role() 

改为:

$user->roles() 

或者只是更改模型中的关系名称。如果关系类型是 hasOne,请将其重命名为 user(),因为它始终只有一个角色,不需要复数。

在 Laravel8 一对多获取用户和评论之间的数据时出现错误

UserController.php BEFORE

 $comment = User::find($id)->comments;  
 return $comment;

UserController.php AFTER

$comment = User::find($id)->comment;  
 return $comment;