array_pluck与模型结果Laravel

问题描述 投票:1回答:1

我的应用程序上有索引功能,它显示了一个包含所有用户的表:

public function index(Request $request)
{
    $this->authorize('inet.user.view');
    $users = User::with(['roles', 'groups'])->paginate(10);

    return view('security.users.index', compact('users'));
}

但是当我尝试制作组和角色列表时,我有很多错误。这是表:

<table class="table table-responsive" id="users-table">
    <thead>
        <th>
            @lang('table.generic.name')
        </th>
        <th>
            @lang('table.users.role') & @lang('table.users.group')
        </th>
    </thead>
    <tbody>
        @foreach($users as $user)
        <tr>
            <td>
                {!! $user->fullname !!}
            </td>
            <td>
                {!! ---HERE NEED TO SHOW LIST OF ROLES--- !!}
            </td>
        </tr>
       @endforeach
   </tbody>
</table>

我试图加入implode(', ', theMethod)并获得与array_pluck($user, 'roles.name')的名称,但不起作用,$user->pluck('roles.name')也没有。

如何在视图中不执行for的情况下获取角色和组列表?

php laravel
1个回答
2
投票

只需遍历使用with()方法加载的嵌套集合:

@foreach($user->roles as $role)
    {{ $role->name }}
@endforeach

@foreach($user->groups as $group)
    {{ $group->name }}
@endforeach

如果你想使用implode(),请使用pluck()获取名称:

implode(', ', $user->roles->pluck('name')->toArray())
© www.soinside.com 2019 - 2024. All rights reserved.