在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):jeremykenedy/laravel-roles开源软件地址(OpenSource Url):https://github.com/jeremykenedy/laravel-roles开源编程语言(OpenSource Language):PHP 54.5%开源软件介绍(OpenSource Introduction):Laravel RolesA Powerful package for handling roles and permissions in Laravel. Supports Laravel 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 6.0, 7.0, and 8.0+. Table of contents
Features
InstallationThis package is very easy to set up. There are only couple of steps. ComposerFrom your projects root folder in terminal run: Laravel 5.8 and up use:
Laravel 5.7 and below use:
Service Provider
'providers' => [
...
/**
* Third Party Service Providers...
*/
jeremykenedy\LaravelRoles\RolesServiceProvider::class,
], Publish All Assets php artisan vendor:publish --tag=laravelroles Publish Specific Assets php artisan vendor:publish --tag=laravelroles-config
php artisan vendor:publish --tag=laravelroles-migrations
php artisan vendor:publish --tag=laravelroles-seeds
php artisan vendor:publish --tag=laravelroles-views
php artisan vendor:publish --tag=laravelroles-lang HasRoleAndPermission Trait And Contract
Example <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use jeremykenedy\LaravelRoles\Traits\HasRoleAndPermission;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
use HasRoleAndPermission;
// rest of your model ...
} Migrations and seeds
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Database\Seeders\PermissionsTableSeeder;
use Database\Seeders\RolesTableSeeder;
use Database\Seeders\ConnectRelationshipsSeeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
$this->call(PermissionsTableSeeder::class);
$this->call(RolesTableSeeder::class);
$this->call(ConnectRelationshipsSeeder::class);
//$this->call('UsersTableSeeder');
Model::reguard();
}
}
composer dump-autoload
php artisan db:seed Roles Seeded
Permissions Seeded:
And that's it!Migrate from bican rolesIf you migrate from bican/roles to jeremykenedy/LaravelRoles you will need to update a few things.
UsageCreating Roles$adminRole = config('roles.models.role')::create([
'name' => 'Admin',
'slug' => 'admin',
'description' => '',
'level' => 5,
]);
$moderatorRole = config('roles.models.role')::create([
'name' => 'Forum Moderator',
'slug' => 'forum.moderator',
]);
Attaching, Detaching and Syncing RolesIt's really simple. You fetch a user from database and call $user = config('roles.models.defaultUser')::find($id);
$user->attachRole($adminRole); // you can pass whole object, or just an id
$user->detachRole($adminRole); // in case you want to detach role
$user->detachAllRoles(); // in case you want to detach all roles
$user->syncRoles($roles); // you can pass Eloquent collection, or just an array of ids Assign a user role to new registered usersYou can assign the user a role upon the users registration by updating the file
protected function create(array $data)
{
$user = config('roles.models.defaultUser')::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$role = config('roles.models.role')::where('name', '=', 'User')->first(); //choose the default role upon user creation.
$user->attachRole($role);
return $user;
} Checking For RolesYou can now check if the user has required role. if ($user->hasRole('admin')) { // you can pass an id or slug
//
} You can also do this: if ($user->isAdmin()) {
//
} And of course, there is a way to check for multiple roles: if ($user->hasRole(['admin', 'moderator'])) {
/*
| Or alternatively:
| $user->hasRole('admin, moderator'), $user->hasRole('admin|moderator'),
| $user->hasOneRole('admin, moderator'), $user->hasOneRole(['admin', 'moderator']), $user->hasOneRole('admin|moderator')
*/
// The user has at least one of the roles
}
if ($user->hasRole(['admin', 'moderator'], true)) {
/*
| Or alternatively:
| $user->hasRole('admin, moderator', true), $user->hasRole('admin|moderator', true),
| $user->hasAllRoles('admin, moderator'), $user->hasAllRoles(['admin', 'moderator']), $user->hasAllRoles('admin|moderator')
*/
// The user has all roles
} LevelsWhen you are creating roles, there is optional parameter if ($user->level() > 4) {
//
}
Creating PermissionsIt's very simple thanks to $createUsersPermission = config('roles.models.permission')::create([
'name' => 'Create users',
'slug' => 'create.users',
'description' => '', // optional
]);
$deleteUsersPermission = config('roles.models.permission')::create([
'name' => 'Delete users',
'slug' => 'delete.users',
]); Attaching, Detaching and Syncing PermissionsYou can attach permissions to a role or directly to a specific user (and of course detach them as well). $role = config('roles.models.role')::find($roleId);
$role->attachPermission($createUsersPermission); // permission attached to a role
$user = config('roles.models.defaultUser')::find($userId);
$user->attachPermission($deleteUsersPermission); // permission attached to a user $role->detachPermission($createUsersPermission); // in case you want to detach permission
$role->detachAllPermissions(); // in case you want to detach all permissions
$role->syncPermissions($permissions); // you can pass Eloquent collection, or just an array of ids
$user->detachPermission($deleteUsersPermission);
$user->detachAllPermissions();
$user->syncPermissions($permissions); // you can pass Eloquent collection, or just an array of ids Checking For Permissionsif ($user->hasPermission('create.users')) { // you can pass an id or slug
//
}
if ($user->canDeleteUsers()) {
//
} You can check for multiple permissions the same way as roles. You can make use of additional methods like Permissions InheritanceBy default, roles with higher level inherit all permissions from roles with lower level. For example: You have three roles:
Entity CheckLet's say you have an article and you want to edit it. This article belongs to a user (there is a column use App\Article;
$editArticlesPermission = config('roles.models.permission')::create([
'name' => 'Edit articles',
'slug' => 'edit.articles',
'model' => 'App\Article',
]);
$user->attachPermission($editArticlesPermission);
$article = Article::find(1);
if ($user->allowed('edit.articles', $article)) { // $user->allowedEditArticles($article)
//
} This 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. if ($user->allowed('edit.articles', $article, false)) { // now owner check is disabled
//
} Blade ExtensionsThere are four Blade extensions. Basically, it is replacement for classic if statements. @role('admin') // @if(Auth::check() && Auth::user()->hasRole('admin'))
// user has admin role
@endrole
@permission('edit.articles') // @if(Auth::check() && Auth::user()->hasPermission('edit.articles'))
// user has edit articles permissison
@endpermission
@level(2) // @if(Auth::check() && Auth::user()->level() >= 2)
// user has level 2 or higher
@endlevel
@allowed('edit', $article) // @if(Auth::check() && Auth::user()->allowed('edit', $article))
// show edit button
@endallowed
@role('admin|moderator', true) // @if(Auth::check() && Auth::user()->hasRole('admin|moderator', true))
// user has admin and moderator role
@else
// something else
@endrole MiddlewareThis package comes with /**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'role' => \jeremykenedy\LaravelRoles\App\Http\Middleware\VerifyRole::class,
'permission' => \jeremykenedy\LaravelRoles\App\Http\Middleware\VerifyPermission::class,
'level' => \jeremykenedy\LaravelRoles\App\Http\Middleware\VerifyLevel::class,
]; Now you can easily protect your routes. Route::get('/', function () {
//
})->middleware('role:admin');
Route::get('/', function () {
//
})->middleware('permission:edit.articles');
Route::get('/', function () {
//
})->middleware('level:2'); // level >= 2
Route::get('/', function () {
//
})->middleware('role:admin', 'level:2'); // level >= 2 and Admin
Route::group(['middleware'
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论