{"id":18658767,"url":"https://github.com/shanmuga3/laravel-entrust","last_synced_at":"2025-04-12T19:41:27.668Z","repository":{"id":38389418,"uuid":"236187321","full_name":"shanmuga3/laravel-entrust","owner":"shanmuga3","description":"Handle Role-based Permissions for your Laravel application","archived":false,"fork":false,"pushed_at":"2025-03-13T04:47:18.000Z","size":62,"stargazers_count":65,"open_issues_count":0,"forks_count":19,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-05T18:04:26.100Z","etag":null,"topics":["access-control","entrust","laravel","laravel-application","role-permissions"],"latest_commit_sha":null,"homepage":"","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/shanmuga3.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-01-25T15:20:29.000Z","updated_at":"2025-03-13T04:42:05.000Z","dependencies_parsed_at":"2024-06-18T16:42:09.486Z","dependency_job_id":"c9801901-3887-4369-9b27-6fc5df6ab938","html_url":"https://github.com/shanmuga3/laravel-entrust","commit_stats":{"total_commits":35,"total_committers":7,"mean_commits":5.0,"dds":0.6,"last_synced_commit":"d7c9c1787ffc4f8b5005f1cd2c145e17f392a573"},"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shanmuga3%2Flaravel-entrust","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shanmuga3%2Flaravel-entrust/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shanmuga3%2Flaravel-entrust/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shanmuga3%2Flaravel-entrust/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/shanmuga3","download_url":"https://codeload.github.com/shanmuga3/laravel-entrust/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248624961,"owners_count":21135509,"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":["access-control","entrust","laravel","laravel-application","role-permissions"],"created_at":"2024-11-07T07:34:16.135Z","updated_at":"2025-04-12T19:41:27.632Z","avatar_url":"https://github.com/shanmuga3.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Laravel Entrust (Supports Laravel 5 to 10)\nHandle Role-based Permissions for your Laravel application.\n\n## Version Compatibility\n\n| Laravel       | Laravel Entrust                                           |\n| :------------ | :-------------------------------------------------- |\n| 10.x          | [4.x]         |\n| 9.x           | [3.x]         |\n| 8.x           | [2.x]         |\n| 7.x - 5.x     | [1.x]         |\n\n## Contents\n\n- [Installation \u0026 Configuration](#installation)\n- [Usage](#usage)\n    - [Concepts](#concepts)\n        - [Checking for Roles \u0026 Permissions](#checking-for-roles--permissions)\n        - [User ability](#user-ability)\n    - [Middleware](#middleware)\n- [Troubleshooting](#troubleshooting)\n- [License](#license)\n- [Contribution guidelines](#contribution-guidelines)\n- [Additional information](#additional-information)\n\n## Installation\n\n1) You can install the Laravel-entrust package via composer:\n\n```bash\ncomposer require shanmuga/laravel-entrust\n```\n\u003e **Note:** You Can Skip step 2 and 3 If you are using above Laravel 5.5.\n\n2) Open your `config/app.php` and add the following to the `providers` array:\n\n```php\nShanmuga\\LaravelEntrust\\LaravelEntrustServiceProvider::class,\n```\n\n3) In the same `config/app.php` and add the following to the `aliases ` array: \n\n```php\n'LaravelEntrust'   =\u003e Shanmuga\\LaravelEntrust\\Facades\\LaravelEntrustFacade::class,\n```\n\n4) Run the command below to publish the package config files `config/entrust.php` and `config/entrust_seeder.php`\n\n```shell\nphp artisan vendor:publish --tag=\"LaravelEntrust\"\n```\n\n5) Open your `config/entrust.php` and add the following to it:\n\nName of the migration file to be generated\n```php\n'migrationSuffix' =\u003e 'laravel_entrust_setup_tables',\n```\nModel and Table Used for Authorization\n```php\n'user_model' =\u003e 'App\\Models\\User',\n'user_table' =\u003e 'users',\n```\nName of the Models Used for Role and Permission\n```php\n'models' =\u003e [\n    'role'          =\u003e 'App\\Models\\Role',\n    'permission'    =\u003e 'App\\Models\\Permission',\n],\n```\nDefault Guard to perform user authentication, You Can also pass it manually when checking it.\n```php\n'defaults' =\u003e [\n     'guard'          =\u003e 'web',\n ],\n```\nYou can also use multiple guards: \n```php\n'defaults' =\u003e [\n     'guard'          =\u003e ['web', 'api'],\n ],\n```\nTable names used for roles and permissions\n```php\n'tables' =\u003e [\n    'roles'             =\u003e 'roles',\n    'permissions'       =\u003e 'permissions',\n    'role_user'         =\u003e 'role_user',\n    'permission_role'   =\u003e 'permission_role',\n],\n```\nForiegn keys used for roles and permissions\n```php\n'foreign_keys' =\u003e [\n    'user' =\u003e 'user_id',\n    'role' =\u003e 'role_id',\n    'permission' =\u003e 'permission_id',\n],\n```\nMiddleware Setup for custom message, register set to true for register automatically, **Handling** is which handler to be used either *abort* or *redirect*. you can also configure what message should be display if authorization failed.\n```php\n'middleware' =\u003e [\n    'register' =\u003e true,\n    'handling' =\u003e 'abort',\n    'handlers' =\u003e [\n        'abort' =\u003e [\n            'code' =\u003e 403,\n            'message' =\u003e 'You don\\'t Have a permission to Access this page.'\n        ],\n        'redirect' =\u003e [\n            'url' =\u003e '/',\n            'message' =\u003e [\n                'key' =\u003e 'error',\n                'content' =\u003e 'You don\\'t Have a permission to Access this page'\n            ]\n        ],\n    ],\n],\n```\n\n6)  Run the following command to generate migration and seed\n\n```bash\nphp artisan laravel-entrust:setup\n```\n\u003e See [Entrust Seeder](#entrust_seeder) Configuration to learn more about create permissions.\n\n7)  Finally Add the LaravelEntrustUserTrait to existing `User` model. For example:\n```php\n\u003c?php\n\nuse Shanmuga\\LaravelEntrust\\Traits\\LaravelEntrustUserTrait;\n\nclass User extends Model\n{\n    use LaravelEntrustUserTrait; // add this trait to your user model\n\n    ...\n}\n```\nThis will enable the relation with `Role` and add the following methods `roles()`, `hasRole($name)`, `hasPermission($permission)`, and `ability($roles, $permissions, $options)` within your `User` model.\n\nDon't forget to dump composer autoload\n\n```bash\ncomposer dump-autoload\n```\n\n**And you are ready to go.**\n\n#### Soft Deleting\n\nThe default migration takes advantage of `onDelete('cascade')` clauses within the pivot tables to remove relations when a parent record is deleted. If for some reason you cannot use cascading deletes in your database, the EntrustRole and EntrustPermission classes, and the HasRole trait include event listeners to manually delete records in relevant pivot tables. In the interest of not accidentally deleting data, the event listeners will **not** delete pivot data if the model uses soft deleting. However, due to limitations in Laravel's event listeners, there is no way to distinguish between a call to `delete()` versus a call to `forceDelete()`. For this reason, **before you force delete a model, you must manually delete any of the relationship data** (unless your pivot tables uses cascading deletes). For example:\n\n```php\n$role = Role::findOrFail(1); // Pull back a given role\n\n// Regular Delete\n$role-\u003edelete(); // This will work no matter what\n\n// Force Delete\n$role-\u003eusers()-\u003esync([]); // Delete relationship data\n$role-\u003epermissions()-\u003esync([]); // Delete relationship data\n\n$role-\u003eforceDelete(); // Now force delete will work regardless of whether the pivot table has cascading delete\n```\n\n## Usage\n\n### Concepts\nLet's start by configuring `entrust_seeder` to create role and permissions:\nYour  `config/laratrust_seeder.php`  file looks like this:\n\n```php\n\u003c?php\nreturn [\n    'role_structure' =\u003e [\n        'admin' =\u003e [\n            'users' =\u003e 'c,r,u,d',\n            'admin' =\u003e 'c,r,u,d',\n            'profile' =\u003e 'r,d'\n        ],\n        'subadmin' =\u003e [\n            'users' =\u003e 'c,r,u',\n            'profile' =\u003e 'r,u'\n        ],\n    ],\n    'user_roles' =\u003e [\n        'admin' =\u003e [\n            ['name' =\u003e \"Admin\", \"email\" =\u003e \"admin@demo.com\", \"password\" =\u003e '123456'],\n        ],\n    ],\n    'permissions_map' =\u003e [\n        'c' =\u003e 'create',\n        'r' =\u003e 'read',\n        'u' =\u003e 'update',\n        'd' =\u003e 'delete',\n    ],\n];\n```\n\nNow Users are created and alse roles and it's permissions are assigned to that users.\nYou Can also attach and detach role is as easy as:\n\n```php\n$user = User::where('username', 'shan')-\u003efirst();\n\n// role attach alias\n$user-\u003eattachRole($admin); // parameter can be an Role object, array, or id\n\n// or eloquent's original technique\n$user-\u003eroles()-\u003eattach($admin-\u003eid); // id only\n```\n#### Checking for Roles \u0026 Permissions\n\nNow we can check for roles and permissions simply by doing:\n\n```php\n$user-\u003ehasRole('owner');   // false\n$user-\u003ehasRole('admin');   // true\n$user-\u003ehasPermission('edit-user');   // false\n$user-\u003ehasPermission('create-post'); // true\n```\n\nBoth `hasRole()` and `hasPermission()` can receive an array of roles \u0026 permissions to check:\n\n```php\n$user-\u003ehasRole(['owner', 'admin']);       // true\n$user-\u003ehasPermission(['edit-user', 'create-post']); // true\n```\nBy default, if any of the roles or permissions are present for a user then the method will return true.\nPassing `true` as a second parameter instructs the method to require **all** of the items:\n\n```php\n$user-\u003ehasRole(['owner', 'admin']);             // true\n$user-\u003ehasRole(['owner', 'admin'], true);       // false, user does not have admin role\n$user-\u003ehasPermission(['edit-user', 'create-post']);       // true\n$user-\u003ehasPermission(['edit-user', 'create-post'], true); // false, user does not have edit-user permission\n```\nYou can have as many `Role`s as you want for each `User` and vice versa.\n\nThe `Entrust` class has shortcuts to both `can()` and `hasRole()` for the currently logged in user:\n\n```php\nEntrust::hasRole('role-name');\nEntrust::can('permission-name');\nEntrust::hasPermission('permission-name');\n\n// is identical to\nAuth::user()-\u003ehasRole('role-name');\nAuth::user()-\u003ecan('permission-name');\nAuth::user()-\u003ehasPermission('permission-name');\nAuth::user()-\u003eisAbleTo('permission-name');\n```\n\nYou can also use placeholders (wildcards) to check any matching permission by doing:\n\n```php\n// match any permission about users\n$user-\u003ehasPermission(\"*-users\"); // true\n```\n\n#### User ability\n\nMore advanced checking can be done using the awesome `ability` function.\nIt takes in three parameters (roles, permissions, options):\n- `roles` is a set of roles to check.\n- `permissions` is a set of permissions to check.\n\nEither of the roles or permissions variable can be a comma separated string or array:\n\n```php\n$user-\u003eability(['admin', 'owner'], ['create-user', 'edit-user']);\n// or\n$user-\u003eability('admin,owner', 'create-user,edit-user');\n```\nThis will check whether the user has any of the provided roles and permissions.\nIn this case it will return true since the user is an `admin` and has the `create-user` permission.\n\nThe third parameter `validateAll` is a boolean flag to set whether to check all the values for true, or to return true if at least one role or permission is matched. It is optional and by default it is `false`.\n\n### Middleware\nYou can use a middleware to filter routes and route groups by permission or role\n```php\nRoute::group(['prefix' =\u003e 'admin', 'middleware' =\u003e ['role:admin']], function() {\n    Route::get('/', [AdminController::class,'welcome']);\n    Route::get('/view', [AdminController::class,'manageAdmins'])-\u003emiddleware('permission:view-admin');\n});\n```\n\nIt is possible to use pipe symbol as *OR* operator:\n```php\n'middleware' =\u003e ['role:admin|root']\n```\nTo emulate *AND* functionality just use multiple instances of middleware\n```php\n'middleware' =\u003e ['role:owner', 'role:writer']\n```\n## Troubleshooting\n\nIf you encounter an error when doing the migration that looks like:\n```\nSQLSTATE[HY000]: General error: 1005 Can't create table 'laravelbootstrapstarter.#sql-42c_f8' (errno: 150)\n    (SQL: alter table `role_user` add constraint role_user_user_id_foreign foreign key (`user_id`)\n    references `users` (`id`)) (Bindings: array ())\n```\nThis occur when use laravel less than 5.8. It uses `Integer` for migration autoIncrement but laravel entrust uses `BigInteger`. So make sure both are  same..\n\nWhen trying to use the EntrustUserTrait methods, you encounter the error which looks like\n\n    Class name must be a valid object or a string\n\nthen probably you don't have published Entrust assets or something went wrong when you did it.\nFirst of all check that you have the `entrust.php` file in your `config` directory.\nIf you don't, then try `php artisan vendor:publish --tag=LaravelEntrust` and, if it does not appear, manually copy the `/vendor/shanmuga/laravel-entrust/src/config/entrust.php` file in your config directory.\n\nIf your app uses a custom namespace then you'll need to tell entrust where your `permission` and `role` models are, you can do this by editing the config file in `config/entrust.php`\n\n```\n'models' =\u003e [\n     'role'          =\u003e 'App\\Models\\Role',\n     'permission'    =\u003e 'App\\Models\\Permission',\n ]\n ```\n## License\n\nLaravel-Entrust is free software distributed under the terms of the MIT license.\n\n## Contribution guidelines\n\nSupport follows PSR-1 and PSR-4 PHP coding standards, and semantic versioning.\n\nPlease report any issue you find in the issues page.  \nPull requests are always welcome.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshanmuga3%2Flaravel-entrust","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshanmuga3%2Flaravel-entrust","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshanmuga3%2Flaravel-entrust/lists"}