Import roles & permissions data from Laravel into Javascript.
You can install the package via composer:
composer require timedoor/laravel-role-js
Don't forget to install jeremykenedy/laravel-roles package to use default setting.
You can publish the config file with:
php artisan vendor:publish --tag="laravel-role-js-config"
This is the contents of the published config file:
return [
'generator' => timedoor\RoleJs\Generator\JeremyKenedyRoleGenerator::class,
];
First, publish the JavaScript files that contain logic for roles and permissions. The files will publish to resources/js/roles
path.
php artisan role-js:publish
if you want to change the publish path, spesify the path in the command.
php artisan role-js:publish your/publish/path/roles
Second, run the command to generate the JavaScript file contains roles & permissions data. It will generate file data.ts
in the publish path.
php artisan role-js:generate
You can also spesify the publish path in the command.
php artisan role-js:generate your/publish/path/roles
You can use the generated file in your JavaScript code.
import { HasRolePermission, useRoles } from 'resources/js/roles';
// Example user data with one role
const admin: HasRolePermission = {
roles: 'admin',
};
const { hasRole, hasPermission } = useRoles(admin);
// Check if user has the given role
if (hasRole('admin')) {
// Do something
}
// check if user has one of the given roles
if (hasRole(['admin', 'editor'])) {
// Do something
}
// check if user has a permission
if (hasPermission('edit.users')) {
// Do something
}
// check if user has one of the given permissions
if (hasPermission(['view.users', 'edit.users'])) {
// Do something
}
// check if user has all of the given permissions
if (hasPermission(['view.users', 'edit.users'], true)) {
// Do something
}
You can create your own generator by implementing timedoor\RoleJs\Generator\GeneratorInterface
interface.
<?php
namespace App\RoleJs;
use timedoor\RoleJs\Generator\GeneratorInterface;
class CustomRoleGenerator implements GeneratorInterface
{
/**
* @return \Illuminate\Support\Collection<int, string>
*/
public function getRoles()
{
return collect(['admin', 'editor']);
}
/**
* @return \Illuminate\Support\Collection<int, string>
*/
public function getPermissions()
{
return collect(['view.users', 'edit.users']);
}
/**
* @return \Illuminate\Support\Collection<string, string[]>
*/
public function getRolePermissions()
{
return collect([
'admin' => ['view.users', 'edit.users'],
'editor' => ['view.users'],
]);
}
}
Then, change the generator class in the config file.
return [
'generator' => App\RoleJs\CustomRoleGenerator::class,
];
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.