itstructure / laravel-rbac
Laravel package for RBAC manage
Requires
- php: >=7.3.0
- itstructure/laravel-grid-view: ^1.3.1
- laravel/framework: ^8.0|^9.0|^10.0|^11.0|^12.0|^13.0
Requires (Dev)
- orchestra/testbench: ^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
- phpunit/phpunit: ^9.5|^10.0|^11.0|^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
1 Introduction
LaRbac - Package for the Laravel framework which provides management with the next data:
- Roles
- Permissions
- Assign roles for users
2 Dependencies
- laravel 8+ | 9+ | 10+ | 11+ | 12+ | 13+
- Bootstrap 4 or 5 for styling
- php >= 7.3.0
- composer
3 Installation
Note!
Version 3.x is for laravel 8+, 9+, 10+, 11+, 12+, 13+.
Version 2.x is for laravel 6 or 7. You can use branch laravel67-rbac with 2.x versions.
3.1 General installation from remote repository
Run the composer command:
composer require itstructure/laravel-rbac "^3.1.2"
3.2 Next internal installation steps
Notes:
-
Make sure that a table for the users is already existing in your project.
-
Make sure that a model for the users table is already existing in your project.
Recommendation:
If you don't have any layout yet, it is useful to install for example AdminLTE or you can make your special any layout template. Cause in this package there is no a layout specially. But in config it is necessary to set it (see the next point 2 about a configure).
Let's go:
-
Publish files.
Note:
rbac.phpconfig file and seedersLaRbacDatabaseSeeder,PermissionSeeder,RoleSeedermust be published surely!-
To publish config run command:
php artisan rbac:publish --only=configIt stores config file to
configfolder. -
To publish seeders run command:
php artisan rbac:publish --only=seedersIt stores seeder files to
database/seedersfolder. -
To publish migrations run command:
php artisan rbac:publish --only=migrationsIt stores migration files to
database/migrationsfolder. -
To publish views run command:
php artisan rbac:publish --only=viewsIt stores view files to
resources/views/vendor/rbacfolder.Note! If you published views before version 3.1.0, publish them again with
--forceargument. Version 3.1.0 fixed a security issue inusers/index.blade.php: a user name was displayed without escaping. -
To publish translations run command:
php artisan rbac:publish --only=langIt stores translation files to
resources/lang/vendor/rbacfolder. -
To publish all parts run command without
onlyargument:php artisan rbac:publish
Else you can use
--forceargument to rewrite already published files. -
-
Configure published
config/rbac.phpfile:-
set
layout. Example:'layout' => 'adminlte::page' -
change
userModelClassif it is needed to change -
set
adminUserIdwhich you wanted to be with the role of administrator. At least at the beginning stage.It is necessary for the next time system to let you go into the Rbac control panel, after you assigned an administrator role for you (Later see point 5).
-
Most likely you have to change
memberNameAttributeKey.It is to display the user name in control panel by
getMemberNameAttribute()method ofAdministrabletrait.By default it is
'name': a column of the users table. It can be a string or a callback.String (recommended). A column name or a name of an accessor in your
Usermodel. For example, to display a first and a last name, add an accessor to theUsermodel:public function getFullNameAttribute(): string { return $this->first_name . ' ' . $this->last_name; }
And set in config:
'memberNameAttributeKey' => 'full_name',
Callback:
'memberNameAttributeKey' => function ($row) { return $row->first_name . ' ' . $row->last_name; }
Note! With a callback the command
php artisan config:cache(andphp artisan optimize) does not work: Laravel can not save a function to the config cache. So in production use a string. Before version 3.1.0 the default value was a callback. If you published the config earlier and useconfig:cache, change it to a string.
-
-
Tuning your
Usermodel (as shown in 4.1 point):-
Implement
Usermodel fromRbacUserInterface. -
Add roles attribute to
$fillable. -
Apply
Administrabletrait.
-
-
Run command to run migrations and seeders:
php artisan rbac:databaseOr optional:
To run just migrations
php artisan rbac:database --only=migrateTo run just seeds
php artisan rbac:database --only=seed-
Alternative variant for seeders.
You can set published rbac
LaRbacDatabaseSeederseeder class in to a specialDatabaseSeeder:use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder { public function run() { $this->call(LaRbacDatabaseSeeder::class); } }
and run command:
php artisan db:seed.
-
-
Run command to set Admin role for user with identifier
adminUserId, defined in 2 point:php artisan rbac:admin
4 Usage
Notes:
-
Make sure you use Bootstrap 4 or Bootstrap 5 for styling in your application. The views work with both versions, for example with Laravel-AdminLTE v3 (Bootstrap 4) and v4 (Bootstrap 5). JQuery is not needed.
-
Make sure that a laravel initial factory authorization is already working in your application.
4.1 Model part
According with the Itstructure\LaRbac\Interfaces\RbacUserInterface use functions from Itstructure\LaRbac\Traits\Administrable trait as in example:
namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Itstructure\LaRbac\Interfaces\RbacUserInterface; use Itstructure\LaRbac\Traits\Administrable;
class User extends Authenticatable implements RbacUserInterface { use Notifiable, Administrable; protected $fillable = [ 'name', 'email', 'password', 'roles' ]; protected $hidden = [ 'password', 'remember_token', ]; }
4.2 Routes part
There are already integrated base RBAC routes to manage users, roles and permissions. See in routes.php package file.
They are guarded by the next:
- middleware
auth(editable by config). - permission
can:administrate(editable by config).
This routes allow you to go to the next routes:
-
Users section
For get request method
http://example-domain.com/rbac/usershttp://example-domain.com/rbac/users/show/{id}http://example-domain.com/rbac/users/edit/{id}
For post request method
http://example-domain.com/rbac/users/update/{id}http://example-domain.com/rbac/users/delete
-
Roles section
For get request method
http://example-domain.com/rbac/roleshttp://example-domain.com/rbac/roles/show/{id}http://example-domain.com/rbac/roles/createhttp://example-domain.com/rbac/roles/edit/{role}
For post request method
http://example-domain.com/rbac/roles/storehttp://example-domain.com/rbac/roles/update/{role}http://example-domain.com/rbac/roles/delete
-
Permissions section
For get request method
http://example-domain.com/rbac/permissionshttp://example-domain.com/rbac/permissions/show/{id}http://example-domain.com/rbac/permissions/createhttp://example-domain.com/rbac/permissions/edit/{permission}
For post request method
http://example-domain.com/rbac/permissions/storehttp://example-domain.com/rbac/permissions/update/{permission}http://example-domain.com/rbac/permissions/delete
4.3 Gates part
There are already integrated base RBAC gates to access control in your application to some of the resources. See provider file RbacAuthServiceProvider.php.
It provides the next gate definitions:
administrateassign-roledelete-memberview-recordcreate-recordupdate-recorddelete-recordpublish-record
How the record gates view-record, update-record, delete-record work:
- A user, whose role has this permission, can do it with any record.
- A user without this permission can do it only with his own record. For that your record model must implement
Itstructure\LaRbac\Interfaces\RbacModelInterface: methodgetAuthorIdAttribute()returns an identifier of the record author.
Example:
@can('update-record', $post) <a href="{{ route('posts.edit', $post) }}">Edit</a> @endcan
Note! Before version 3.1.0 these three gates worked wrong: a user with the permission was not allowed to work with a record of another author, and a call without a record (@can('update-record')) made an error.
Read more in Laravel gates
5 View examples
Users
Roles
Permissions
6 Tests
The package has its own tests. They check roles, permissions, gates, controllers (pages, saving, validation, access) and console commands.
Good to know before you start:
- By default the tests do not need a database server and do not need a
.envfile. They use SQLite in memory, everything is created and deleted automatically. - The tests work on all supported versions: PHP 7.3 ... 8.5 and Laravel 8 ... 13.
- When you install dependencies of the package, the
vendorfolder and thecomposer.lockfile appear in the package folder. It is normal. They are in.gitignore, so they will not get into git.
Below there are several ways to run the tests. Choose the one, which fits you.
6.1 Way 1. You have PHP and Composer on your computer
-
Get the package source code.
If you have git, run command:
git clone https://github.com/itstructure/laravel-rbac.gitIf you do not have git, open https://github.com/itstructure/laravel-rbac, press the green Code button, then Download ZIP, and unpack the archive.
-
Go to the package folder:
cd laravel-rbac -
Install dependencies (it is enough to do it once):
composer installComposer itself chooses the Laravel and PHPUnit versions, which fit your PHP version.
Note! PHP must have
pdo_sqliteandmbstringextensions. Usually they are already enabled. If not, Composer or the tests will tell you about it. -
Run the tests:
composer testOr the same directly:
- Linux / macOS:
vendor/bin/phpunit - Windows:
vendor\bin\phpunit
- Linux / macOS:
-
If you want to run only one test, add
--filterwith the test name:vendor/bin/phpunit --filter test_record_gates_with_permission
If everything is fine, you will see a message like: OK (32 tests, 130 assertions).
6.2 Way 2. You have nothing except Docker
You do not need to install PHP and Composer. Docker downloads them by itself.
-
Get the package source code and go to the package folder, as in steps 1 and 2 of Way 1.
-
Install dependencies (it is enough to do it once).
For Linux, macOS and WSL terminal:
docker run --rm --user "$(id -u):$(id -g)" -e COMPOSER_HOME=/tmp/composer -v "$PWD":/app -w /app composer:2 composer update --no-interaction
For Windows PowerShell:
docker run --rm -v "${PWD}:/app" -w /app composer:2 composer update --no-interaction
Here:
--user "$(id -u):$(id -g)"- files in thevendorfolder will belong to you, not to therootuser. In Windows PowerShell it is not needed.-v "$PWD":/app- the current folder (package folder) is available inside the container as/app.
-
Run the tests.
For Linux, macOS and WSL terminal:
docker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/app -w /app php:8.4-cli php vendor/bin/phpunit
For Windows PowerShell:
docker run --rm -v "${PWD}:/app" -w /app php:8.4-cli php vendor/bin/phpunit
To run only one test, add
--filter test_nameto the end of the command.
Note! In step 2 Composer installs the newest versions of Laravel and PHPUnit. They need a new PHP, so in step 3 use php:8.4-cli or newer. To check an old PHP or Laravel version, see Way 3.
6.3 Way 3. Check a specific PHP and Laravel version with Docker
It is useful, when you want to make sure that the package works for example on PHP 7.3 with Laravel 8.
-
Choose a pair of versions from the table:
PHP image Laravel Testbench php:7.3-cli8.*6.*php:8.0-cli9.*7.*php:8.1-cli10.*8.*php:8.2-cli11.*9.*php:8.3-cli12.*10.*php:8.3-cli13.*11.*Testbench (
orchestra/testbench) is a tool for testing Laravel packages. Each Laravel version needs its own Testbench version, that is why it is in the table. -
Go to the package folder. If you have already installed dependencies before, delete the
vendorfolder and thecomposer.lockfile. -
Install dependencies for the chosen pair. Example for PHP 7.3 + Laravel 8 (Linux, macOS, WSL terminal):
docker run --rm --user "$(id -u):$(id -g)" -e COMPOSER_HOME=/tmp/composer -v "$PWD":/app -w /app composer:2 sh -c "composer config platform.php 7.3.33 && composer config policy.advisories.block false && composer require --no-update 'laravel/framework:8.*' && composer require --dev --no-update 'orchestra/testbench:6.*' && composer update --no-interaction --no-plugins"
What this command does:
composer config platform.php 7.3.33- tells Composer to choose packages for PHP 7.3, because Composer itself works on a newer PHP inside its container.composer config policy.advisories.block false- allows installing old Laravel versions. New Composer refuses to install versions with known security advisories. It is OK for running tests, but never do it in a real project.composer require --no-update ...- sets the chosen Laravel and Testbench versions.--no-plugins- old Laravel versions bring Composer plugins, which are not needed for tests and are blocked by new Composer.
For another pair, change
7.3.33,8.*and6.*to the values from the table. Forplatform.phpyou can write any version of the chosen PHP, for example8.0.30,8.2.0. -
Run the tests with the PHP image from the table:
docker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/app -w /app php:7.3-cli php vendor/bin/phpunit
-
Important! The command in step 3 changes the
composer.jsonfile of the package. When you finish, return it back and delete the installed files:git checkout composer.jsonAnd delete the
vendorfolder and thecomposer.lockfile.If you downloaded the package as ZIP (without git), just download and unpack it again.
6.4 Way 4. Run the tests on PostgreSQL or MySQL
By default the tests use SQLite. But the package migrations work a little differently on different databases (they check the primary key type of the users table). So it is useful to check a real database server too.
Set environment variables before running the tests:
| Variable | Value |
|---|---|
RBAC_TEST_DB |
pgsql or mysql |
RBAC_TEST_DB_HOST |
server host, by default 127.0.0.1 |
RBAC_TEST_DB_PORT |
by default 5432 for pgsql, 3306 for mysql |
RBAC_TEST_DB_DATABASE |
by default rbac_test |
RBAC_TEST_DB_USERNAME |
by default root |
RBAC_TEST_DB_PASSWORD |
by default empty |
Important! Use an empty database only for tests. Before each test all tables in it are deleted.
Example with a temporary PostgreSQL in Docker (Linux, macOS, WSL terminal):
-
Start a temporary PostgreSQL server:
docker run -d --rm --name rbac-test-pg -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=rbac_test postgres:17
-
Run the tests (PHP must have
pdo_pgsqlextension):RBAC_TEST_DB=pgsql RBAC_TEST_DB_PORT=55432 RBAC_TEST_DB_USERNAME=postgres RBAC_TEST_DB_PASSWORD=secret vendor/bin/phpunit
-
Stop the server (it is deleted automatically, because of
--rm):docker stop rbac-test-pg
6.5 Way 5. Automatic tests on GitHub
You do not need to do anything. After each push and each pull request, GitHub runs the tests by itself on all version pairs from the table above (and a few more), and also on PostgreSQL and MySQL.
Results are on the Actions tab of the repository: https://github.com/itstructure/laravel-rbac/actions
Green check mark - all tests passed. Red cross - something is broken, open it to see the details.
The settings are in the .github/workflows/tests.yml file.
6.6 If the package is installed in your Laravel project
-
Your project tests and the package tests do not mix.
When you run tests of your project (
composer test,php artisan testorvendor/bin/phpunitin the project folder), only tests of your project are run. The projectphpunit.xmlfile points to the projecttestsfolder, and the package lies invendor/itstructure/laravel-rbac. So the package tests are not run there. -
Usually there are no package tests in your project at all.
By default Composer downloads the package as an archive. The
testsfolder, the.githubfolder and thephpunit.xml.distfile are excluded from this archive (see the.gitattributesfile), because they are not needed for the package to work. So invendor/itstructure/laravel-rbacthere is only the package itself. -
Exception: installation with
--prefer-sourceor from a local folder.If the package is installed with
--prefer-source(Composer makesgit cloneinstead of downloading an archive), or from a local folder ("type": "path"repository), then the whole repository is in the project, the tests too.It does not break anything: your project tests still do not run them.
-
How to run the package tests in this case.
Do not run them through your project, the project has no tools needed for the package tests.
Run them in the package folder itself, as described in Way 1 or Way 2:
- If the package is installed from a local folder (
"type": "path"), go to that local folder. - Otherwise, just clone the package repository to a separate folder.
- If the package is installed from a local folder (
License
Copyright © 2018-2026 Andrey Girnik girnikandrey@gmail.com.
Licensed under the MIT license. See LICENSE.txt for details.
