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

标签 laravel roles

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

在我的用户 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')); 

但是我有这个错误

enter image description here

如果我 dd($users);

我可以看到角色在那里

enter image description here

我该如何解决这个问题?谢谢!

编辑:用户模型

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]此集合实例上不存在”

用户表迁移

enter image description here

角色和权限表迁移

enter image description here

回答

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

相关文章:

php - 数据库中有授权规则的原因是什么?

asp.net-mvc - 关于管理员[授权]属性的问题

jquery - Laravel mix 未捕获引用错误 : jQuery is not defined

php - 如何使 HHVM 的 MySQL 驱动程序将 ID 返回为整数?

perl - 如何用 UML 正确地表示 mixin/role/trait?

spring-security - Spring Security 角色前缀和自定义用户详细信息服务

c# - 如何清除 Sitecore 中的安全角色?

php - Laravel 正则表达式验证价格或为空

laravel - 我如何在 Laravel 4.2 中为多个开发人员使用一条 git 路线

javascript - 从 laravel 5 中的另一个目录获取 Assets