Hướng dẫn user role php - vai trò người dùng php

Trong bất kỳ hệ thống nào, việc phân quyền là một điều hết sức quan trọng. Việc phân quyền sẽ quy định người dùng có thể truy cập những chức năng nào, thực hiện những tác vụ nào trong hệ thống.

Hôm nay mình sẽ hướng dẫn các bạn tạo một hệ thống phân quyền đơn giản nhưng khá đầy đủ, sử dụng trong Laravel.

1. Bài toán

Phân quyền quản lý các bài viết trong blog: create, view, update, delete, restore, force delete.

Một user có nhiều role, một role có nhiều permission.

2. Chuẩn bị

2.1 Database Struct

Chúng ta sẽ cần các bảng: users, roles, permissions, role_user và permission_role

Schema::create['users', function [Blueprint $table] {
    $table->bigIncrements['id'];
    $table->string['name'];
    $table->string['email']->unique[];
    $table->timestamp['email_verified_at']->nullable[];
    $table->string['password'];
    $table->rememberToken[];
    $table->timestamps[];
}];

Schema::create['roles', function [Blueprint $table] {
    $table->increments['id'];
    $table->string['name'];
}];

Schema::create['permissions', function [Blueprint $table] {
    $table->increments['id'];
    $table->string['name'];
}];

Schema::create['role_user', function [Blueprint $table] {
    $table->unsignedInteger['user_id'];
    $table->unsignedInteger['role_id'];

    $table->foreign['user_id']->references['id']->on['users']
        ->onDelete['cascade'];
    $table->foreign['role_id']->references['id']->on['roles']
        ->onDelete['cascade'];
}];

Schema::create['permission_role', function [Blueprint $table] {
    $table->unsignedInteger['permission_id'];
    $table->unsignedInteger['role_id'];

    $table->foreign['permission_id']->references['id']->on['permissions']
        ->onDelete['cascade'];
    $table->foreign['role_id']->references['id']->on['roles']
        ->onDelete['cascade'];
}];

Schema::create['posts', function [Blueprint $table] {
    $table->bigIncrements['id'];
    $table->unsignedInteger['user_id'];
    $table->string['title'];
    $table->text['content'];
    $table->string['status'];
    $table->timestamps[];

    $table->foreign['user_id']->references['id']->on['users']
        ->onDelete['cascade'];
}];

2.2 Trait HasPermissions

app/Traits/HasPermissions.php

Bài Viết Liên Quan

Chủ Đề