{"id":28438099,"url":"https://github.com/zanysoft/laravel-roles","last_synced_at":"2025-09-09T15:42:53.343Z","repository":{"id":57089318,"uuid":"170494421","full_name":"zanysoft/laravel-roles","owner":"zanysoft","description":"A Powerful package for handling roles and permissions in Laravel","archived":false,"fork":false,"pushed_at":"2020-09-21T16:57:08.000Z","size":25,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-06T00:43:13.398Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zanysoft.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-02-13T11:12:52.000Z","updated_at":"2020-09-21T16:56:40.000Z","dependencies_parsed_at":"2022-08-20T16:00:46.553Z","dependency_job_id":null,"html_url":"https://github.com/zanysoft/laravel-roles","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/zanysoft/laravel-roles","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zanysoft%2Flaravel-roles","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zanysoft%2Flaravel-roles/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zanysoft%2Flaravel-roles/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zanysoft%2Flaravel-roles/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zanysoft","download_url":"https://codeload.github.com/zanysoft/laravel-roles/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zanysoft%2Flaravel-roles/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262452331,"owners_count":23313421,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-06-06T00:39:15.868Z","updated_at":"2025-06-28T15:31:40.976Z","avatar_url":"https://github.com/zanysoft.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Roles And Permissions For Laravel.\n[![Laravel](https://img.shields.io/badge/Laravel-5.x-orange.svg?style=flat-square)](http://laravel.com)\n[![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://tldrlegal.com/license/mit-license)\n[![Downloads](https://img.shields.io/packagist/dt/zanysoft/laravel-roles.svg?style=flat-square)](https://packagist.org/packages/zanysoft/laravel-roles)\n\nA Powerful package for handling roles and permissions in Laravel.\n\n- [Installation](#installation)\n    - [Composer](#composer)\n    - [Service Provider](#service-provider)\n    - [Config File And Migrations](#config-file-and-migrations)\n    - [HasRoleAndPermission Trait And Contract](#hasroleandpermission-trait-and-contract)\n    - [Migrations and Seeds](#migrations-and-seeds)\n    - [Migrate from Bican roles](#Migrate-from-bican-roles)\n- [Usage](#usage)\n    - [Creating Roles](#creating-roles)\n    - [Attaching, Detaching and Syncing Roles](#attaching-detaching-and-syncing-roles)\n    - [Assign a user role to new registered users](#assign-a-user-role-to-new-registered-users)\n    - [Checking For Roles](#checking-for-roles)\n    - [Creating Permissions](#creating-permissions)\n    - [Attaching, Detaching and Syncing Permissions](#attaching-detaching-and-syncing-permissions)\n    - [Checking For Permissions](#checking-for-permissions)\n    - [Permissions Inheriting](#permissions-inheriting)\n    - [Entity Check](#entity-check)\n    - [Blade Extensions](#blade-extensions)\n    - [Middleware](#middleware)\n- [Config File](#config-file)\n- [More Information](#more-information)\n- [Opening an Issue](#opening-an-issue)\n- [License](#license)\n\n---\n\n## Installation\n\nThis package is very easy to set up. There are only couple of steps.\n\n### Composer\n\nPull this package in through Composer\n```\ncomposer require zanysoft/laravel-roles\n```\n\n### Service Provider\n* Laravel 5.5 and up\nUses package auto discovery feature, no need to edit the `config/app.php` file.\n\n* Laravel 5.4 and below\nAdd the package to your application service providers in `config/app.php` file.\n\n```php\n'providers' =\u003e [\n\n    ...\n\n    /**\n     * Third Party Service Providers...\n     */\n    ZanySoft\\LaravelRoles\\RolesServiceProvider::class,\n\n],\n```\n\n### Config File\n\nPublish the package config file and migrations to your application. Run these commands inside your terminal.\n\n    php artisan vendor:publish --tag=laravelroles\n\n### HasRoleAndPermission Trait And Contract\n\n1. Include `HasRoleAndPermission` trait and also implement `HasRoleAndPermission` contract inside your `User` model. See example below.\n\n2. Include `use ZanySoft\\LaravelRoles\\Traits\\HasRoleAndPermission;` in the top of your `User` model below the namespace and implement the `HasRoleAndPermission` trait. See example below.\n\nExample `User` model Trait And Contract:\n\n```php\n\n\u003c?php\n\nnamespace App;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Notifications\\Notifiable;\nuse ZanySoft\\LaravelRoles\\Traits\\HasRoleAndPermission;\nuse Illuminate\\Foundation\\Auth\\User as Authenticatable;\n\nclass User extends Authenticatable\n{\n    use Notifiable;\n    use HasRoleAndPermission;\n\n    // rest of your model ...\n}\n\n```\n\n### Migrations and seeds\n\u003e This uses the default users table which is in Laravel. You should already have the migration file for the users table available and migrated.\n\n1. Setup the needed tables:\n\n    `php artisan migrate`\n\n2. Update `database\\seeds\\DatabaseSeeder.php` to include the seeds. See example below.\n\n\n```php\n\u003c?php\n\nuse Illuminate\\Database\\Seeder;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass DatabaseSeeder extends Seeder\n{\n    /**\n     * Run the database seeds.\n     *\n     * @return void\n     */\n    public function run()\n    {\n        Model::unguard();\n\n            $this-\u003ecall('PermissionsTableSeeder');\n            $this-\u003ecall('RolesTableSeeder');\n            $this-\u003ecall('ConnectRelationshipsSeeder');\n            //$this-\u003ecall('UsersTableSeeder');\n\n        Model::reguard();\n    }\n}\n\n```\n\n3. Seed an initial set of Permissions, Roles, and Users with roles.\n\n```\ncomposer dump-autoload\nphp artisan db:seed\n```\n\n#### Roles Seeded\n|Property|Value|\n|----|----|\n|Name| Admin|\n|Slug| admin|\n|Description| Admin Role|\n|Level| 5|\n\n|Property|Value|\n|----|----|\n|Name| User|\n|Slug| user|\n|Description| User Role|\n|Level| 1|\n\n|Property|Value|\n|----|----|\n|Name| Unverified|\n|Slug| unverified|\n|Description| Unverified Role|\n|Level| 0|\n\n#### Permissions Seeded:\n|Property|Value|\n|----|----|\n|name|Can View Users|\n|slug|view.users|\n|description|Can view users|\n|model|Permission|\n\n|Property|Value|\n|----|----|\n|name|Can Create Users|\n|slug|create.users|\n|description|Can create new users|\n|model|Permission|\n\n|Property|Value|\n|----|----|\n|name|Can Edit Users|\n|slug|edit.users|\n|description|Can edit users|\n|model|Permission|\n\n|Property|Value|\n|----|----|\n|name|Can Delete Users|\n|slug|delete.users|\n|description|Can delete users|\n|model|Permission|\n\n\n### And that's it!\n\n---\n## Usage\n\n### Creating Roles\n\n```php\nuse ZanySoft\\LaravelRoles\\Models\\Role;\n\n$adminRole = Role::create([\n    'name' =\u003e 'Admin',\n    'slug' =\u003e 'admin',\n    'description' =\u003e '',\n    'level' =\u003e 5,\n]);\n\n$moderatorRole = Role::create([\n    'name' =\u003e 'Forum Moderator',\n    'slug' =\u003e 'forum.moderator',\n]);\n```\n\n\u003e Because of `Slugable` trait, if you make a mistake and for example leave a space in slug parameter, it'll be replaced with a dot automatically, because of `str_slug` function.\n\n### Attaching, Detaching and Syncing Roles\n\nIt's really simple. You fetch a user from database and call `attachRole` method. There is `BelongsToMany` relationship between `User` and `Role` model.\n\n```php\nuse App\\User;\n\n$user = User::find($id);\n\n$user-\u003eattachRole($adminRole); // you can pass whole object, or just an id\n$user-\u003edetachRole($adminRole); // in case you want to detach role\n$user-\u003edetachAllRoles(); // in case you want to detach all roles\n$user-\u003esyncRoles($roles); // you can pass Eloquent collection, or just an array of ids\n```\n\n### Assign a user role to new registered users\n\nYou can assign the user a role upon the users registration by updating the file `app\\Http\\Controllers\\Auth\\RegisterController.php`.\nYou can assign a role to a user upon registration by including the needed models and modifying the `create()` method to attach a user role. See example below:\n\n* Update the top of `app\\Http\\Controllers\\Auth\\RegisterController.php`:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers\\Auth;\n\nuse App\\User;\nuse App\\Http\\Controllers\\Controller;\nuse Illuminate\\Support\\Facades\\Validator;\nuse ZanySoft\\LaravelRoles\\Models\\Role;\nuse ZanySoft\\LaravelRoles\\Models\\Permission;\nuse Illuminate\\Foundation\\Auth\\RegistersUsers;\n\n```\n\n* Updated `create()` method of `app\\Http\\Controllers\\Auth\\RegisterController.php`:\n\n```php\n    protected function create(array $data)\n    {\n        $user = User::create([\n            'name' =\u003e $data['name'],\n            'email' =\u003e $data['email'],\n            'password' =\u003e bcrypt($data['password']),\n        ]);\n\n        $role = Role::where('name', '=', 'User')-\u003efirst();  //choose the default role upon user creation.\n        $user-\u003eattachRole($role);\n\n        return $user;\n\n    }\n```\n\n### Checking For Roles\n\nYou can now check if the user has required role.\n\n```php\nif ($user-\u003ehasRole('admin')) { // you can pass an id or slug\n    //\n}\n```\n\nYou can also do this:\n\n```php\nif ($user-\u003eisAdmin()) {\n    //\n}\n```\n\nAnd of course, there is a way to check for multiple roles:\n\n```php\nif ($user-\u003ehasRole(['admin', 'moderator'])) {\n    /*\n    | Or alternatively:\n    | $user-\u003ehasRole('admin, moderator'), $user-\u003ehasRole('admin|moderator'),\n    | $user-\u003ehasOneRole('admin, moderator'), $user-\u003ehasOneRole(['admin', 'moderator']), $user-\u003ehasOneRole('admin|moderator')\n    */\n\n    // The user has at least one of the roles\n}\n\nif ($user-\u003ehasRole(['admin', 'moderator'], true)) {\n    /*\n    | Or alternatively:\n    | $user-\u003ehasRole('admin, moderator', true), $user-\u003ehasRole('admin|moderator', true),\n    | $user-\u003ehasAllRoles('admin, moderator'), $user-\u003ehasAllRoles(['admin', 'moderator']), $user-\u003ehasAllRoles('admin|moderator')\n    */\n\n    // The user has all roles\n}\n```\n\n### Creating Permissions\n\nIt's very simple thanks to `Permission` model.\n\n```php\nuse ZanySoft\\LaravelRoles\\Models\\Permission;\n\n$createUsersPermission = Permission::create([\n    'name' =\u003e 'Create users',\n    'slug' =\u003e 'create.users',\n    'description' =\u003e '', // optional\n]);\n\n$deleteUsersPermission = Permission::create([\n    'name' =\u003e 'Delete users',\n    'slug' =\u003e 'delete.users',\n]);\n```\n\n### Attaching, Detaching and Syncing Permissions\n\nYou can attach permissions to a role or directly to a specific user (and of course detach them as well).\n\n```php\nuse App\\User;\nuse ZanySoft\\LaravelRoles\\Models\\Role;\n\n$role = Role::find($roleId);\n$role-\u003eattachPermission($createUsersPermission); // permission attached to a role\n\n```\n\n```php\n$role-\u003edetachPermission($createUsersPermission); // in case you want to detach permission\n$role-\u003edetachAllPermissions(); // in case you want to detach all permissions\n$role-\u003esyncPermissions($permissions); // you can pass Eloquent collection, or just an array of ids\n\n```\n\n### Checking For Permissions\n\n```php\nif ($user-\u003ehasPermission('create.users')) { // you can pass an id or slug\n    //\n}\n\nif ($user-\u003ecanDeleteUsers()) {\n    //\n}\n```\n\nYou can check for multiple permissions the same way as roles. You can make use of additional methods like `hasOnePermission` or `hasAllPermissions`.\n\n### Permissions Inheriting\n\nRole with higher level is inheriting permission from roles with lower level.\n\nThere is an example of this `magic`:\n\nYou have three roles: `user`, `moderator` and `admin`. User has a permission to read articles, moderator can manage comments and admin can create articles.\n\n\u003e If you don't want permissions inheriting feature in you application, simply ignore `level` parameter when you're creating roles.\n\n### Entity Check\n\nLet's say you have an article and you want to edit it. This article belongs to a user (there is a column `user_id` in articles table).\n\n```php\nuse App\\Article;\nuse ZanySoft\\LaravelRoles\\Models\\Permission;\n\n$editArticlesPermission = Permission::create([\n    'name' =\u003e 'Edit articles',\n    'slug' =\u003e 'edit.articles',\n    'model' =\u003e 'App\\Article',\n]);\n\n$role-\u003eattachPermission($editArticlesPermission);\n\n$article = Article::find(1);\n\nif ($user-\u003eallowed('edit.articles', $article)) { // $user-\u003eallowedEditArticles($article)\n    //\n}\n```\n\nThis condition checks if the current user is the owner of article. If not, it will be looking inside user permissions for a row we created before.\n\n```php\nif ($user-\u003eallowed('edit.articles', $article, false)) { // now owner check is disabled\n    //\n}\n```\n\n### Blade Extensions\n\nThere are four Blade extensions. Basically, it is replacement for classic if statements.\n\n```php\n@role('admin') // @if(Auth::check() \u0026\u0026 Auth::user()-\u003ehasRole('admin'))\n    // user has admin role\n@endrole\n\n@permission('edit.articles') // @if(Auth::check() \u0026\u0026 Auth::user()-\u003ehasPermission('edit.articles'))\n    // user has edit articles permissison\n@endpermission\n\n@allowed('edit', $article) // @if(Auth::check() \u0026\u0026 Auth::user()-\u003eallowed('edit', $article))\n    // show edit button\n@endallowed\n\n@role('admin|moderator', true) // @if(Auth::check() \u0026\u0026 Auth::user()-\u003ehasRole('admin|moderator', true))\n    // user has admin and moderator role\n@else\n    // something else\n@endrole\n```\n\n### Helper Functions\n\nThere are four Blade extensions. Basically, it is replacement for classic if statements.\n\n```php\n@if(hasRole('admin')) // @if(Auth::check() \u0026\u0026 Auth::user()-\u003ehasRole('admin'))\n    // user has admin role\n@endif\n\n@if(can('edit.articles')) // @if(Auth::check() \u0026\u0026 Auth::user()-\u003ehasPermission('edit.articles'))\n    // user has edit articles permissison\n@endif\n\n@if(can('create.articles|edit.articles',true)) // @if(Auth::check() \u0026\u0026 Auth::user()-\u003ehasPermission('create.articles|edit.articles'))\n    // user has create and edit articles permissison\n@endif\n\n@if(hasPermission('edit.articles')) // @if(Auth::check() \u0026\u0026 Auth::user()-\u003ehasPermission('edit.articles'))\n    // user has edit articles permissison\n@endif\n\n@if(allowed('edit', $article)) // @if(Auth::check() \u0026\u0026 Auth::user()-\u003eallowed('edit', $article))\n    // show edit button\n@endif\n\n@if(hasRole('admin|moderator', true)) // @if(Auth::check() \u0026\u0026 Auth::user()-\u003ehasRole('admin|moderator', true))\n    // user has admin and moderator role\n@else\n    // something else\n@endif\n```\n\n\n### Middleware\n\nThis package comes with `VerifyRole`, `VerifyPermission` and `VerifyLevel` middleware. You must add them inside your `app/Http/Kernel.php` file.\n\n```php\n/**\n * The application's route middleware.\n *\n * @var array\n */\nprotected $routeMiddleware = [\n    'auth' =\u003e \\App\\Http\\Middleware\\Authenticate::class,\n    'auth.basic' =\u003e \\Illuminate\\Auth\\Middleware\\AuthenticateWithBasicAuth::class,\n    'guest' =\u003e \\App\\Http\\Middleware\\RedirectIfAuthenticated::class,\n    'role' =\u003e \\ZanySoft\\LaravelRoles\\Middleware\\VerifyRole::class,\n    'permission' =\u003e \\ZanySoft\\LaravelRoles\\Middleware\\VerifyPermission::class,\n    'level' =\u003e \\ZanySoft\\LaravelRoles\\Middleware\\VerifyLevel::class,\n];\n```\n\nNow you can easily protect your routes.\n\n```php\nRoute::get('/', function () {\n    //\n})-\u003emiddleware('role:admin');\n\nRoute::get('/', function () {\n    //\n})-\u003emiddleware('permission:edit.articles');\n\nRoute::group(['middleware' =\u003e ['role:admin']], function () {\n    //\n});\n\n```\n\n---\n\n## Config File\nYou can change connection for models, slug separator, models path and there is also a handy pretend feature. Have a look at config file for more information.\n\n## More Information\nFor more information, please have a look at [HasRoleAndPermission](https://github.com/zanysoft/laravel-roles/blob/master/src/Contracts/HasRoleAndPermission.php) contract.\n\n## Opening an Issue\nBefore opening an issue there are a couple of considerations:\n* A **star** on this project shows support and is way to say thank you to all the contributors. If you open an issue without a star, *your issue may be closed without consideration.* Thank you for understanding and the support. You are all awesome!\n* **Read the instructions** and make sure all steps were *followed correctly*.\n* **Check** that the issue is not *specific to your development environment* setup.\n* **Provide** *duplication steps*.\n* **Attempt to look into the issue**, and if you *have a solution, make a pull request*.\n* **Show that you have made an attempt** to *look into the issue*.\n* **Check** to see if the issue you are *reporting is a duplicate* of a previous reported issue.\n* **Following these instructions show me that you have tried.**\n* If you have a questions send me an email to info@zanysoft.com\n\n## License\nThis package is free software distributed under the terms of the MIT license.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzanysoft%2Flaravel-roles","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzanysoft%2Flaravel-roles","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzanysoft%2Flaravel-roles/lists"}