2017-06-17 38 views
3

我想創建用戶,我可以授予權限。 我創建了一個權限模型,其中包含以下屬性(ID |名稱|顯示名|倒序)Laravel使Acl用戶具有權限(無級別/組)

1|xyz.edit|Edit xyz| Allow to edit xyz 
2|xyz.create|Create xyz| Allow to create xyz 

因此,我要像下面創建關係:

public function getPermissions(){ 
    return $this->hasMany('App\Permission'); 
} 

但它不工作。有沒有什麼辦法可以創建像 這樣的關係用戶有很多權限但是沒有爲用戶創建相同的權限? 我可以讓用戶模型像id|pass|login|...|permissions 並與splited權限存儲權限ID「」並在getPermissions()功能做出這樣的事情:

public function getPerms(){ 
    foreach (explode($this->permssions,',')as $id){ 
     //here load from database perm by id add to array and return 
    } 
} 

或第二選項我在本教程https://www.youtube.com/watch?v=Kas2w2DBuFg是讓看另一個表像user_perms與領域

id|user_id|perms|id 

但什麼選擇是最好做到這一點?

回答

0

你可以在你的模型中發佈代碼嗎? (用戶模型和權限模型?)而沒有看到,我看不到你使用的是什麼類型的關係,儘管看起來你使用的是一對多的關係。

無論哪種方式...

也可以讓用戶在分配他們的權限,而不用擔心組的方法是使用一個多到多的關係。這需要3個表格。用戶表,權限表和數據透視表。

您可以瞭解許多一對多的關係,在這裏:https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

但給你一個破敗......

用戶模型

public function permissions(){ 
    return $this->belongsToMany('App\Permission'); 
} 

權限模型

public function users(){ 
    return $this->belongsToMany('App\User'); 
} 

create_users_table遷移(字段名稱並不重要,ju ST請確保您有增量()之一)

$table->increments('id'); 
$table->string('name'); 
(etc, standard migration stuff) 

create_permissions_table遷移(字段名沒有真正的問題,只是確保你有增量()之一)

$table->increments('id'); 
$table->string('name'); 
$table->string('long_name'); 
(etc, standard migration stuff) 

,爲數據透視表,您需要按字母順序使用這兩個表的單數名稱(或者至少,這是默認值)

create_permission_user_table(這兩個字段名稱很重要,laravel預計這些名稱,您不需要任何其他領域...你可以,如果你想徹底)

$table->integer('permission_id'); 
$table->integer('user_id'); 

,然後給用戶一個權限也設置外鍵關係,你只需做

// Grab your user and permission, however you do that... 
$permission = \App\Permission::first(); 
$user = \App\User::first(); 

// Then save the permission to the user (or the other way around, but it makes more sense this way) 
$user->permissions()->save($permission); 

這會讓你有權限的用戶:)

然後你可以通過$ user-> permissions訪問一個權限數組,並執行你需要檢查的任何邏輯檢查是否允許它們做任何事情!

相關問題