【问题标题】:Whats the best way to store user role permissions in Laravel 5? [closed]在 Laravel 5 中存储用户角色权限的最佳方式是什么? [关闭]
【发布时间】:2017-08-12 03:57:53
【问题描述】:

我正在 Laravel 5.2 中构建一个网络应用程序。我对 Laravel 比较陌生,并且想遵循最佳实践。 我有一个名为 Roles 的表,它有几个命名的用户角色(即:管理员、编辑器等)。我希望管理员能够编辑这些角色的权限并创建新角色。存储权限的最佳方式是什么?

  1. 使用整数字段,每一位代表一个权限? (我认为这很快就会失控)
  2. 使用数据透视表和多对多权限连接?
  3. 使用字符串字段并仅序列化选择的权限?

未来可能会添加新的权限,我的目标是能够轻松确定用户是否具有特定角色。即:$user->roles->hasAdmin() 或类似的东西。

【问题讨论】:

  • Laravel 5.2 已过时,不再受支持。如果你正在开发新的应用程序,你应该以 Laravel 5.4 为目标。

标签: php laravel roles privileges


【解决方案1】:

您可能想从Laravel Entrust 包中借用角色/权限表的最佳实践:

    // Create table for storing roles
    Schema::create('{{ $rolesTable }}', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->string('display_name')->nullable();
        $table->string('description')->nullable();
        $table->timestamps();
    });

    // Create table for associating roles to users (Many-to-Many)
    Schema::create('{{ $roleUserTable }}', function (Blueprint $table) {
        $table->integer('user_id')->unsigned();
        $table->integer('role_id')->unsigned();

        $table->foreign('user_id')->references('{{ $userKeyName }}')->on('{{ $usersTable }}')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('role_id')->references('id')->on('{{ $rolesTable }}')
            ->onUpdate('cascade')->onDelete('cascade');

        $table->primary(['user_id', 'role_id']);
    });

    // Create table for storing permissions
    Schema::create('{{ $permissionsTable }}', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->string('display_name')->nullable();
        $table->string('description')->nullable();
        $table->timestamps();
    });

    // Create table for associating permissions to roles (Many-to-Many)
    Schema::create('{{ $permissionRoleTable }}', function (Blueprint $table) {
        $table->integer('permission_id')->unsigned();
        $table->integer('role_id')->unsigned();

        $table->foreign('permission_id')->references('id')->on('{{ $permissionsTable }}')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('role_id')->references('id')->on('{{ $rolesTable }}')
            ->onUpdate('cascade')->onDelete('cascade');

        $table->primary(['permission_id', 'role_id']);
    });

【讨论】:

  • 谢谢,这正是我所需要的!我不需要每个用户的多个角色,但到底是什么,如果将来需要它,它仍然很有用。
猜你喜欢
  • 2011-04-10
  • 2021-09-01
  • 2012-10-03
  • 2023-03-16
  • 2017-10-04
  • 2016-12-18
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
相关资源
最近更新 更多