2017-05-01 93 views
2

我使用Sentinel Framework進行授權和身份驗證。但我堅持用戶管理。Laravel/Sentinel - 如何通過數據透視表獲取價值

我想顯示詳細信息,如電子郵件 - 角色,但我仍然堅持在這裏。

我的數據庫:

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}}] 

一個數組,但我不能訪問到 「塞」 財產:(

我該怎麼做?

非常感謝!

回答

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多對多文檔獲取更多信息:Laravel Many To Many

+0

Hello Mortadda Jafar。感謝您的幫助,但它不起作用。我仍然有一個錯誤的表或視圖未找到:1146表'shop.role_user'不存在(SQL:選擇角色。*,角色用戶。用戶標識爲'pivot_user_id',角色用戶。角色'role_id'作爲'pivot_role_id'來自'角色'內部聯接'角色'角色''''''''''role_user'.'role_id'其中'role_user'.'user_id' = 1)。 –

+0

什麼是「shop.role_user」? –

+0

role_user有2個字段是user_id和role_id。這裏是我的DB |角色:ID,slug ,name |; | user:ID,Email,... |; | role_users:user_id,role_id | –