PHP code example of fereydooni / laravel-user-management

1. Go to this page and download the library: Download fereydooni/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/ */

    

fereydooni / laravel-user-management example snippets


use Fereydooni\LaravelUserManagement\Traits\HasPermissions;

class User extends Authenticatable
{
    use HasPermissions;

    // Set custom user type (optional)
    protected string $userType = 'admin';
}

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

// Create a permission
$permission = Permission::create(['name' => 'edit articles']);

// Assign permission to role
$role->givePermissionTo($permission);

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

use Fereydooni\LaravelUserManagement\Attributes\Authorize;

class ArticleController extends Controller
{
    // Permission-based authorization
    #[Authorize(permission: 'view-articles')]
    public function index()
    {
        // Only users with 'view-articles' permission can access this
    }

    // Role-based authorization
    #[Authorize(role: 'editor')]
    public function create()
    {
        // Only users with 'editor' role can access this
    }

    // User type-based authorization
    #[Authorize(userType: 'manager')]
    public function manage()
    {
        // Only users of type 'manager' can access this
    }

    // Combined authorization
    #[Authorize(permission: 'edit-articles', role: 'editor', userType: 'manager')]
    public function edit()
    {
        // Only manager-type users with editor role and edit-articles permission can access this
    }
}

protected $routeMiddleware = [
    // ...
    'authorize' => \Fereydooni\LaravelUserManagement\Middleware\AuthorizeAttribute::class,
];

Route::middleware('authorize')->group(function () {
    Route::get('/articles', [ArticleController::class, 'index']);
    Route::post('/articles', [ArticleController::class, 'store']);
});

// Check if user has permission
if ($user->hasPermissionTo('edit articles')) {
    // User can edit articles
}

// Check if user has specific role
if ($user->hasRole('editor')) {
    // User has editor role
}

// Check if user is of specific type
if ($user->getUserType() === 'manager') {
    // User is of type manager
}

// Check combined authorization
if ($user->hasPermissionThroughAttribute('edit-articles', 'editor', 'manager')) {
    // User has all 

// Register gates for attribute-based authorization
User::registerAttributeGates();
bash
php artisan vendor:publish --tag=user-management-config