Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
waiyanheincyberduck committed Jun 12, 2020
0 parents commit be3ab7e
Show file tree
Hide file tree
Showing 11 changed files with 451 additions and 0 deletions.
13 changes: 13 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "waiyanhein/lara-role-manager",
"description": "Library to manage the user roles for Laravel",
"license": "MIT",
"authors": [
{
"name": "Wai Yan Hein",
"email": "[email protected]"
}
],
"minimum-stability": "dev",
"require": {}
}
54 changes: 54 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
###Package to manage user roles for Laravel application

Having to write code for managing user roles each time you create a new Laravel project is a repeating project. Sometimes, you will try to copy the existing code form the other projects, such as Role model class.
You will need to create a model class for role, plus, migration file for it. Then you also have to define the relationship between user and role. Then you will have to write methods for related logic for example, checking if the user belongs to a role. This package includes all the necessary common logic and components fo handling user roles for Laravel application.


####installation

- `composer require waiyanhein/lara-role-manager`

####Publishing config file to define roles

- `php artisan vendor:publish`

Then roles.php file will be published under the app/config folder. You can define the roles in the following format.

`
[
1 => 'Superadmin',
2 => 'Manager',
3 => 'Staff'
]
`
The array key is the unique code and the value is the title to be displayed to the end users.

####Migrating the table
- Then you migrate the tables for the roles. `php artisan migrate`

####Usages

You will need to place the `Waiyanhein\LaraRoleManager\Traits\RoleManager` trait into the user model class.

####Seeding data (Optional)
If you are seeding the roles into the database, you can seed the data from the `config/roles.php` calling the following method in your seeder class.
- `\Waiyanhein\LaraRoleManager\LaraRolesSeeder::seed();`

####Methods
Then you can use the following methods based on your need.

`Waiyanhein\LaraRoleManager\Models\Role` class

- `findRole($code)` - static method. This method will return the role based on the code. $code is the unique code defined in the `config/roles.php` file mapped to the displayed title.
- `users()` - This method is the Eloquent relationship. You can leverage all the features of Eloquent on this method. For example, `$role->users()->get()`.
- `roles()` - static method. This method will return all the roles in the `id` => `displayed title` mapping. Return type is array.

`Waiyanhein\LaraRoleManager\Traits\RoleManager` trait

You embed this trait into your user model class so that your user model class can leverage all the features of this trait.

- `roles()` - This method is the Eloquent relationship. You can leverage all the features of Eloquent on this method. For example: `$user->roles()->get()`.
- `attachRole($code)` - This will attach a role to the user. $code is the unique code defined in the `config/roles.php` file mapped to the displayed title. For example: `$user->attachRole(User::ROLE_ADMIN)`;
- `attachRoles($codes)` - This is similar to `attachRole` function. Instead, you pass an array of codes to assign multiple roles to the user at the same time.
- `hasRole($code)` - Checks if the user has a role. This method will return boolean value. For example: `$user->hasRole(User::ROLE_ADMIN)`.
- `hasRoles($codes)`. This method is very similar to `hasRole` method. Instead, this will check if the user belongs to all the roles which are pass as an array to the method. If any of the role is missing, it will return false.
32 changes: 32 additions & 0 deletions src/LaraRoleManagerServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Waiyanhein\LaraRoleManager;

use Illuminate\Support\ServiceProvider;

class LaraRoleManagerServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}

/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__ . '/roles.php' => config_path('roles.php'),
]);
$this->loadMigrationsFrom(__DIR__ . '/migrations');
$this->loadFactoriesFrom(__DIR__ . '/factories');
}
}
20 changes: 20 additions & 0 deletions src/LaraRolesSeeder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Waiyanhein\LaraRoleManager;

use Waiyanhein\LaraRoleManager\Models\Role;

class LaraRolesSeeder
{
public static function seed()
{
$roles = config('roles');

foreach ($roles as $code => $displayTitle) {
factory(Role::class)->create([
'code' => $code,
'display_title' => $displayTitle,
]);
}
}
}
23 changes: 23 additions & 0 deletions src/factories/RoleFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(\Waiyanhein\LaraRoleManager\Models\Role::class, function (Faker $faker) {
return [
'code' => $faker->unique()->randomNumber(3),
'display_title' => $faker->unique()->word,
];
});
33 changes: 33 additions & 0 deletions src/migrations/2020_06_12_161325_create_roles_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->integer('code')->unique();
$table->string('display_title')->unique();
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
36 changes: 36 additions & 0 deletions src/migrations/2020_06_12_190554_create_user_role_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUserRoleTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_role', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('role_id');
$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user_role');
}
}
29 changes: 29 additions & 0 deletions src/models/Role.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Waiyanhein\LaraRoleManager\Models;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
public static function findRole($code)
{
return static::where('code', $code)->first();
}

public function users()
{
$this->belongsToMany(config('auth.providers.users.model'), 'user_role', 'role_id', 'user_id')->withTimestamps();
}

public static function roles()
{
$roles = [ ];
$roleModels = static::all();
foreach ($roleModels as $roleModel) {
$roles[$roleModel->id] = $roleModel->display_title;
}

return $roles;
}
}
13 changes: 13 additions & 0 deletions src/roles.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

return [
//@todo: define your roles here,
//example
/*
[
1 => 'Super admin',
2 => 'Manager',
3 => 'Staff',
]
*/
];
51 changes: 51 additions & 0 deletions src/traits/RoleManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Waiyanhein\LaraRoleManager\Traits;

use Waiyanhein\LaraRoleManager\Models\Role;

trait RoleManager
{
public function roles()
{
return $this->belongsToMany(\Waiyanhein\LaraRoleManager\Models\Role::class, 'user_role', 'user_id', 'role_id')->withTimestamps();
}

public function attachRole($code)
{
$role = Role::where('code', $code)->first();

if (! $role) {
throw new \LogicException("Invalid code passed to attachRole function. Code: $code");
}

$this->roles()->attach([ $role->id ]);
}

public function attachRoles($codes)
{
$validCodes = [ ];
foreach ($codes as $code) {
if (! $this->hasRole($code)) {
$validCodes[] = $code;
}
}
$roleIds = Role::whereIn('code', $validCodes)->get()->pluck('id')->all();

if ($roleIds) {
$this->roles()->attach($roleIds);
}
}

public function hasRole($code)
{
$role = $this->roles()->where('code', $code)->first();

return ($role)? true: false;
}

public function hasRoles($codes)
{
return $this->roles()->whereIn('code', $codes)->count() == count($codes);
}
}
Loading

0 comments on commit be3ab7e

Please sign in to comment.