PHP code example of mark-villudo / laravel-user-management

1. Go to this page and download the library: Download mark-villudo/laravel-user-management library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mark-villudo / laravel-user-management example snippets



// Assign role to specific user
$user->assignRole('writer');


$user->canAccess('View','Users');

'providers' => [
    // ...
    MarkVilludo\Permission\PermissionServiceProvider::class,
];

return [

    'models' => [

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * Eloquent model should be used to retrieve your permissions. Of course, it
         * is often just the "Permission" model but you may use whatever you like.
         *
         * The model you want to use as a Permission model needs to implement the
         * `MarkVilludo\Permission\Contracts\Permission` contract.
         */

        'permission' => MarkVilludo\Permission\Models\Permission::class,

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * Eloquent model should be used to retrieve your roles. Of course, it
         * is often just the "Role" model but you may use whatever you like.
         *
         * The model you want to use as a Role model needs to implement the
         * `MarkVilludo\Permission\Contracts\Role` contract.
         */

        'role' => MarkVilludo\Permission\Models\Role::class,

    ],

    'table_names' => [

        /*
         * The table that your application uses for users. This table's model will
         * be using the "HasRoles" and "HasPermissions" traits.
         */

        'users' => 'users',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your roles. We have chosen a basic
         * default value but you may easily change it to any table you like.
         */

        'roles' => 'roles',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your permissions. We have chosen a basic
         * default value but you may easily change it to any table you like.
         */

        'permissions' => 'permissions',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your users permissions. We have chosen a
         * basic default value but you may easily change it to any table you like.
         */

        'user_has_permissions' => 'user_has_permissions',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your users roles. We have chosen a
         * basic default value but you may easily change it to any table you like.
         */

        'user_has_roles' => 'user_has_roles',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your roles permissions. We have chosen a
         * basic default value but you may easily change it to any table you like.
         */

        'role_has_permissions' => 'role_has_permissions',
    ],

    'foreign_keys' => [
        
        /*
         * The name of the foreign key to the users table.
         */
        'users' => 'user_id',
    ],

    /*
     *
     * By default we'll make an entry in the application log when the permissions
     * could not be loaded. Normally this only occurs while installing the packages.
     *
     * If for some reason you want to disable that logging, set this value to false.
     */

    'log_registration_exception' => true,
];



namespace App;


use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use MarkVilludo\Permission\Traits\HasRoles;
use MarkVilludo\Permission\Models\Permission;
use MarkVilludo\Permission\Models\RoleHasPermission;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'email', 'password', 'is_expire_access', 'expiration_date',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    public function scopeFilterByName($query, $key)
    {
        return $query->where('first_name', 'like', '%' . $key . '%')
            ->orWhere('last_name', 'like', '%' . $key . '%')
            ->orWhere('email', 'like', '%' . $key . '%');
    }

    //get by roles
    public function scopeFilterByRole($query, $role)
    {
        if ($role) {
            return  $query->withAndWhereHas('roles', function ($query) use ($role) {
                    $query->where('id', $role);
            });
        }
    }

    //for withandwherehas
    public function scopeWithAndWhereHas($query, $relation, $constraint)
    {
        return $query->whereHas($relation, $constraint)->with([$relation => $constraint]);
    }
    
    public static function checkAccess($permissionName, $moduleName)
    {
        // return $permissionName.'-'.$moduleName;
        $roleIds = auth()->user()->roles->pluck('id');
        //get permission id base on permission and module name
        $permissionData = Permission::where('name', $permissionName)
                                        ->where('module', $moduleName)
                                        ->first();
        if ($permissionData) {
            $checkIfHasPermission = RoleHasPermission::whereIn('role_id', $roleIds)
                                        ->where('permission_id', $permissionData->id)
                                        ->first();

            if ($checkIfHasPermission) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}



use MarkVilludo\Permission\Models\Role;

$role = Role::create(['name' => 'writer']);


$permissions = $user->permissions;
$roles = $user->roles()->pluck('name'); // Returns a collection

$users = User::role('writer')->get(); // Only returns users with the role 'writer'

$user->canAccess('Add','Users');

$user->assignRole('writer');

// You can also assign multiple roles at once
$user->assignRole('writer', 'admin');
$user->assignRole(['writer', 'admin']);

$user->removeRole('writer');

// All current roles will be removed from the user and replace by the array given
$user->syncRoles(['writer', 'admin']);

$user->hasRole('writer');

$user->hasAnyRole(Role::all());

$user->hasAllRoles(Role::all());

$role->givePermissionTo('edit articles');

$role->hasPermissionTo('edit articles');

$role->revokePermissionTo('edit articles');

// Direct permissions
$user->getDirectPermissions() // Or $user->permissions;

// Permissions inherited from user's roles
$user->getPermissionsViaRoles();

// All permissions which apply on the user
$user->getAllPermissions();

@role('writer')
    I'm a writer!
@else
    I'm not a writer...
@endrole

@hasrole('writer')
    I'm a writer!
@else
    I'm not a writer...
@endhasrole

@hasanyrole(Role::all())
    I have one or more of these roles!
@else
    I have none of these roles...
@endhasanyrole

@hasallroles(Role::all())
    I have all of these roles!
@else
    I don't have all of these roles...
@endhasallroles

@if(auth()->user()->checkAccess('View', 'Users'))
    <button class="btn btn-success btn-custom waves-effect w-md waves-light m-b-5 pull-left">View User</button>
@endif


use Auth;

// ...

public function handle($request, Closure $next, $role, $permission)
{
    if (Auth::guest()) {
        return redirect($urlOfYourLoginPage);
    }

    if (! $request->user()->hasRole($role)) {
       abort(403);
    }
    
    return $next($request);
}

protected $routeMiddleware = [
    // ...
    'role' => \App\Http\Middleware\RoleMiddleware::class,
    // ...
];

Route::group(['middleware' => ['role:admin,access_backend']], function () {
    //
});
bash
php artisan vendor:publish --provider="MarkVilludo\Permission\PermissionServiceProvider" --tag="migrations"
bash
$ php artisan migrate
bash
php artisan vendor:publish --provider="MarkVilludo\Permission\PermissionServiceProvider" --tag="seeder"
bash
php artisan vendor:publish --provider="MarkVilludo\Permission\PermissionServiceProvider" --tag="config"
bash
php artisan vendor:publish --provider="MarkVilludo\Permission\PermissionServiceProvider" --tag="views"
bash
php artisan vendor:publish --provider="MarkVilludo\Permission\PermissionServiceProvider" --tag="assets"

  return 
        [
            'id' => $this->id,
            'name' => $this->name,
            'permissions' => $this->permissions
        ];


//ute::group(['middleware' => 'auth'], function() {

	Route::resource('users', '\MarkVilludo\Permission\Controllers\UserController');
	Route::resource('roles', '\MarkVilludo\Permission\Controllers\RoleController');
	Route::resource('permissions', '\MarkVilludo\Permission\Controllers\PermissionController');
});

 bash
$ php artisan make:middleware RoleMiddleware