Laravel / Sentinel - 如何通过数据透视表获取价值

时间:2017-05-01 08:34:11

标签: php laravel sentinel

我使用Sentinel Framework进行授权和身份验证。但我坚持使用用户管理。

我希望显示详细信息,例如电子邮件 - 角色,但我仍然坚持到这里。

我的数据库:

role: ID, slug, name
user: ID, Email, ...
role_users: user_id, role_id

我的控制器

  public function getAll(){
    $user = User::all();
    return view('admin.user.list',['user'=>$user]);
}

我的UserModel

public function Role(){
    return $this->belongsToMany('App\Role','role_users','user_id', 'role_id');
}

然后我的观点

<?php foreach ($user as $u): ?>
<tr>
 <td>{{$u->Role->name}}</td>
</tr>
<?php endforeach; ?>

然后我收到了错误

Property [slug] does not exist on this collection instance. 

如果我写

<td>{{$u->Role}}</td>

它出现了像

这样的数组
[{"id":1,"slug":"admin","name":"admin","permissions":null,"created_at":null,"updated_at":null,"pivot":{"user_id":1,"role_id":1}}]

但是我无法访问“slug”属性:(

我该怎么做?

非常感谢!!!

1 个答案:

答案 0 :(得分:0)

用户模型

class User extends Model
    {
        /**
         * The roles that belong to the user.
         */
        public function roles()
        {
            return $this->belongsToMany('App\Role');
        }
    }

角色模型

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

控制器

 public function getAll(){
    $user = User::all();
    return view('admin.user.list',['user'=>$user]);
}

查看

@foreach ($user as $u)
    // becuase many to many you need this
   @foreach ($u->roles as $role) 
         {{$role->name}}
   @endforeach
@endforeach

查看Laravel Many To Many文档以获取更多信息:Laravel Many To Many