Laravel选择用户角色和功能并列出它们

时间:2015-05-12 18:36:29

标签: php laravel

我想确定每个用户的角色并将其显示在表格中。

我想要的输出是这样的:

output

因此表头Functie必须是表name内数据库表列roles的函数名。

我的控制器:

public function index()
    {

        $select_all_users = DB::table('users')->orderBy('username', 'DESC')->get();

        foreach ($select_all_users as $users) {

            //make an array object of the news
            $users = array();

            $select_user_role = DB::table('users')
            ->join('roles', 'users.role_id', '=', 'roles.id')
            ->select('roles.id', 'roles.name', 'roles.description', 'roles.color')
            ->where('username', '=', Auth::user()->username)
            ->first();
        }



        return View::make('admin.users.index')->with('select_user', $select_all_users);
    }

我知道$ select_user_role只会占用用户会话的值......

所以现在我想要按用户列出它们。

我的观点:

<tbody>

                            @foreach($select_user as $user)

                            <td>{{ ucfirst($user->username) }}</td>

                            <td>{{ ucfirst($user->last_name) }}</td>

                            <td>{{ $user->email }}</td>

                            <td>Here needs to come the role name</td>

                            <td>{{ $user->status }}</td>

                            <td>{{ strftime('%A %d %B %Y', $user->registered_at) }}</td>

                            <td>{{ strftime('%A %d %B %Y', $user->last_login) }}</td>

                            <td><a href="{{ URL::to('admin/user/' . $user->id . '/edit') }}" class="btn btn-sm yellow">Bewerk <i class="fa fa-edit"></i></a></td>

                            <td>
                            {{ Form::open(['method' => 'delete',  'route' => ['admin.user.destroy', $user->id]]) }}
                                {{ Form::button('Verwijderen <i class="fa fa-user-times"></i>', array('type' => 'submit', 'class' => 'btn btn-sm red')) }}
                            {{ Form::close() }}

                            </td>

                            </tr>
                            @endforeach

                            </tbody>

1 个答案:

答案 0 :(得分:3)

首先:为您的用户模型添加关系:

class User extends Model {

    // ...

    public function role()
    {
        return $this->belongsTo('App\Role'); // apply your namespace accordingly
    }
}

然后,在您的控制器中,使用预先加载来让所有用户获得他们的角色:

public function index()
{
    $select_all_users = User::with('role')->get();

    return View::make('admin.users.index')->with('select_user', $select_all_users);
}