定制 mimaxuz/role-manager 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mimaxuz/role-manager

Composer 安装命令:

composer require mimaxuz/role-manager

包简介

Simple Laravel roles and permissions for Laravel applications

README 文档

README

An easy and flexible Laravel authorization and roles permission management.

Total Downloads License

About

In many projects, you have to work with roles and permissions. Many packages are large and not all features are needed. That's why I tried to create a small but effective package for projects. This package can be attached to any project. Convenient and efficient. It is very easy to use and can be used after installation.

Requirements

  • PHP >= 8.0.2
  • Laravel >= 10.0

Installation

Step 1: Install via Composer

composer require mimaxuz/role-manager

Step 2: Run Migrations

php artisan migrate

Step 3: Publish Configuration (Optional)

php artisan vendor:publish --tag=role-manager-config

This will create a config/role-manager.php file where you can customize default roles, permissions, and other settings.

Step 4: Add Trait to User Model

Open your App\Models\User model and add the HasPermissions trait:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use MIMAXUZ\LRoles\Traits\HasPermissions;

class User extends Authenticatable
{
    use HasPermissions;

    // ...
}

Database Structure

This package creates the following tables with cascade relationships:

Database Diagram

Table Description
x_roles Stores role definitions (name, slug)
x_permissions Stores permission definitions (name, slug)
roles_permissions Pivot table linking roles to permissions
users_roles Pivot table linking users to roles

Artisan Commands

Role Management

# Create a new role
php artisan role:create "Admin"
php artisan role:create "Super Admin" --slug=super-admin

# List all roles
php artisan role:list
php artisan role:list --with-permissions
php artisan role:list --with-users

# Assign role to user
php artisan role:assign user@example.com admin
php artisan role:assign 1 admin --by=id

# Remove role from user
php artisan role:assign user@example.com admin --remove

Permission Management

# Create a new permission
php artisan permission:create "Edit Users"
php artisan permission:create "Delete Posts" --slug=delete-posts

# List all permissions
php artisan permission:list
php artisan permission:list --with-roles

Attach Permissions to Roles

# Attach single permission
php artisan role:permission admin edit-users

# Attach multiple permissions
php artisan role:permission admin edit-users delete-users view-users

# Detach permissions
php artisan role:permission admin edit-users --detach

# Sync permissions (replace all existing)
php artisan role:permission admin edit-users delete-users --sync

Seed Default Roles & Permissions

# Seed from config
php artisan role:seed

# Fresh seed (clear existing and reseed)
php artisan role:seed --fresh

# Seed only permissions
php artisan role:seed --permissions-only

# Seed only roles
php artisan role:seed --roles-only

Configuration

After publishing the config file, you can customize:

// config/role-manager.php

return [
    // User model class
    'user_model' => App\Models\User::class,

    // Field to lookup users in CLI commands
    'user_lookup_field' => 'email',

    // Default roles to seed
    'default_roles' => [
        [
            'name' => 'Administrator',
            'slug' => 'admin',
            'permissions' => ['*'], // All permissions
        ],
        [
            'name' => 'User',
            'slug' => 'user',
            'permissions' => [],
        ],
    ],

    // Default permissions to seed
    'default_permissions' => [
        ['name' => 'View Users', 'slug' => 'view-users'],
        ['name' => 'Create Users', 'slug' => 'create-users'],
        ['name' => 'Edit Users', 'slug' => 'edit-users'],
        ['name' => 'Delete Users', 'slug' => 'delete-users'],
    ],

    // Roles that have all permissions automatically
    'super_admin_roles' => ['admin'],
];

Usage

Programmatic Usage

Creating Roles & Permissions

use MIMAXUZ\LRoles\Models\XRoles;
use MIMAXUZ\LRoles\Models\XPermissions;

// Create a role
$role = XRoles::create([
    'name' => 'Editor',
    'slug' => 'editor'
]);

// Create a permission
$permission = XPermissions::create([
    'name' => 'Edit Posts',
    'slug' => 'edit-posts'
]);

// Attach permission to role
$role->permissions()->attach($permission->id);

// Or attach multiple permissions
$role->permissions()->attach([1, 2, 3]);

// Sync permissions (replace existing)
$role->permissions()->sync([1, 2, 3]);

Assigning Roles to Users

// Assign a role
$user->roles()->attach($roleId);

// Assign multiple roles
$user->roles()->attach([1, 2]);

// Remove a role
$user->roles()->detach($roleId);

// Sync roles (replace existing)
$user->roles()->sync([1, 2]);

Checking Roles & Permissions

// Check if user has a role
if ($user->hasRole('admin')) {
    // User is admin
}

// Check multiple roles (OR logic)
if ($user->hasRole('admin', 'editor')) {
    // User is admin OR editor
}

// Check if user has permission
if ($user->hasPermissionTo($permission)) {
    // User has the permission
}

// Using Laravel's can() method
if ($user->can('edit-posts')) {
    // User can edit posts
}

Route Middleware

Protect routes using the role middleware:

// Single role
Route::group(['middleware' => 'role:admin'], function () {
    Route::get('/admin/dashboard', [AdminController::class, 'dashboard']);
});

// Role with permission check
Route::group(['middleware' => 'role:admin,delete-users'], function () {
    Route::delete('/users/{id}', [UserController::class, 'destroy']);
});

Blade Directives

@role / @endrole

@role('admin')
    <a href="/admin">Admin Panel</a>
@endrole

@role('editor')
    <a href="/posts/create">Create Post</a>
@endrole

@hasPermission / @endhasPermission

@hasPermission('edit-users')
    <button>Edit User</button>
@endhasPermission

@hasPermission('delete-users')
    <button class="danger">Delete User</button>
@endhasPermission

@hasAnyRole / @endhasAnyRole

@hasAnyRole(['admin', 'editor'])
    <a href="/content">Manage Content</a>
@endhasAnyRole

Using Laravel's @can

@can('edit-posts')
    <button>Edit Post</button>
@endcan

@cannot('delete-posts')
    <span>You cannot delete posts</span>
@endcannot

Quick Start Example

# 1. Install and migrate
composer require mimaxuz/role-manager
php artisan migrate

# 2. Publish config
php artisan vendor:publish --tag=role-manager-config

# 3. Seed default roles and permissions
php artisan role:seed

# 4. Create custom role
php artisan role:create "Content Manager" --slug=content-manager

# 5. Create custom permissions
php artisan permission:create "Publish Posts" --slug=publish-posts
php artisan permission:create "Moderate Comments" --slug=moderate-comments

# 6. Attach permissions to role
php artisan role:permission content-manager publish-posts moderate-comments

# 7. Assign role to user
php artisan role:assign john@example.com content-manager

# 8. View all roles with permissions
php artisan role:list --with-permissions

Available Trait Methods

Method Description
hasRole(...$roles) Check if user has any of the given roles
hasPermissionTo($permission) Check if user has a specific permission
givePermissionsTo(...$permissions) Assign direct permissions to user
withdrawPermissionsTo(...$permissions) Remove permissions from user
refreshPermissions(...$permissions) Replace all user permissions
roles() Get user's roles relationship

Changelog

v2.0.0

  • Added Artisan commands for role and permission management
  • Added configuration file with default roles/permissions
  • Added seeding command (role:seed)
  • Added new Blade directives (@hasPermission, @hasAnyRole)
  • Fixed bugs in HasPermissions trait
  • Laravel 10, 11, 12 support

v1.x

  • Initial release with basic role/permission functionality

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Issues

If you discover any issues or bugs, please report them at GitHub Issues.

License

The MIT License (MIT). Please see License File for more information.

mimaxuz/role-manager 适用场景与选型建议

mimaxuz/role-manager 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 161 次下载、GitHub Stars 达 2, 最近一次更新时间为 2020 年 06 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 mimaxuz/role-manager 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mimaxuz/role-manager 我们能提供哪些服务?
定制开发 / 二次开发

基于 mimaxuz/role-manager 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 161
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 5
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-06-19