PHP code example of obrainwave / access-tree

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

    

obrainwave / access-tree example snippets


use Obrainwave\AccessTree\Traits\HasRole;

class User extends Authenticatable
{
    use HasRole;
}

return [

    // Basic Configuration
    'seed_permissions'            => true,
    'seed_roles'                  => true,
    'assign_first_user_as_admin'  => true,
    'cache_refresh_time'          => 5,
    'forbidden_redirect'          => 'home',

    // User Model Configuration
    'user_model'                  => 'App\\Models\\User',

    // Admin Interface Configuration
    'admin_favicon'               => null, // Path to custom favicon

    // Universal Table Management
    'managed_tables'              => [], // Empty = all tables, or specify: ['posts', 'products', 'orders']
    'dashboard_table_cards'       => [], // Which managed tables show cards on dashboard

    // Styling Configuration
    'styling'                     => [
        'framework'  => 'bootstrap', // bootstrap, tailwind, or custom
        'theme'      => 'modern',    // modern, classic, or minimal
        'dark_mode'  => false,       // Enable dark mode by default
        'animations' => true,        // Enable animations
        'custom_css' => null,        // Custom CSS string
    ],
];

// config/accesstree.php
'assign_first_user_as_admin' => true,

'assign_first_user_as_admin' => false,


namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Obrainwave\AccessTree\Traits\HasRole;

class User extends Authenticatable
{
    use HasRole;
}

use Obrainwave\AccessTree\Facades\AccessTree; or use AccessTree;

// Create permission
AccessTree::createAccess([
    'name' => 'Edit Articles',
    'status' => 1
], 'Permission');

// Create role with permissions
AccessTree::createAccess([
    'name' => 'Editor',
    'status' => 1
], 'Role', [1, 2, 3]); // Permission IDs

// Create permission
createAccess(['name' => 'Delete Articles'], 'Permission');

// Create role
createAccess(['name' => 'Admin'], 'Role', [1, 2, 3, 4]);

$user = User::find(1);

// Assign a single role
$user->assignRole('admin');

// Assign multiple roles
$user->assignRoles(['editor', 'moderator']);

// Sync roles (removes existing, adds new ones)
$user->syncRoles([1, 2, 3]);

// Using helper function
createUserRole([1, 2], $user->id);

// Check single permission
if (checkPermission('edit_articles')) {
    // User has permission
}

// Check multiple permissions (strict - all at least one)
if (checkPermissions(['edit_articles', 'delete_articles'], false)) {
    // User has AT LEAST ONE permission
}

// Check role
if (checkRole('admin')) {
    // User has role
}

// Using model methods
if ($user->hasRole('admin')) {
    // User is admin
}

if ($user->hasPermission('edit_articles')) {
    // User can edit articles
}

@if(checkPermission('edit_articles'))
    <button>Edit Article</button>
@endif

@if(checkRole('admin'))
    <div class="admin-panel">Admin Controls</div>
@endif

@if(checkPermissions(['edit_articles', 'delete_articles'], true))
    <div>User can both edit and delete articles</div>
@endif

// Mark user as root
$user = User::find(1);
$user->is_root_user = true;
$user->save();

// Check if current user is root
if (isRootUser()) {
    // Bypasses all permission checks
}

// Check if specific user is root
if (isRootUser($user->id)) {
    // User has full access
}

// Configure which tables to manage (in config/accesstree.php)
'managed_tables' => [
    'posts',
    'products',
    'orders',
    'categories'
], // Empty array = manage all tables

// config/accesstree.php
'managed_tables' => [
    'posts',
    'products', 
    'orders',
    'user_wallet'
], // Only these tables will appear in sidebar
// Leave empty [] to manage all tables

// config/accesstree.php
'dashboard_table_cards' => [
    'posts',
    'products'
], // Only these will show as cards on dashboard
// Leave empty [] for no table cards

// config/accesstree.php
'admin_favicon' => 'images/favicon.ico',

// config/accesstree.php
'styling' => [
    'framework'  => 'bootstrap', // bootstrap, tailwind, or custom
    'theme'      => 'modern',    // modern, classic, or minimal
    'dark_mode'  => false,       // Default dark mode
    'animations' => true,        // Enable animations
    'custom_css' => null,        // Custom CSS string
    'custom_js'  => null,        // Custom JavaScript string
],

'custom_css' => '
    /* Import Google Fonts */
    @import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap");
    
    /* Brand Colors */
    :root {
        --primary-color: #ff6b6b;
        --secondary-color: #4ecdc4;
        --accent-color: #45b7d1;
    }
    
    /* Custom Logo */
    .admin-logo {
        content: url("/images/company-logo.png");
        width: 120px;
        height: auto;
    }
    
    /* Custom Sidebar */
    .sidebar {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-right: 1px solid rgba(255,255,255,0.1);
    }
    
    /* Custom Buttons */
    .btn-primary {
        background-color: var(--primary-color) !important;
        border-color: var(--primary-color) !important;
        border-radius: 8px;
        font-weight: 500;
    }
    
    .btn-primary:hover {
        background-color: #ff5252 !important;
        border-color: #ff5252 !important;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
    }
    
    /* Custom Cards */
    .card {
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid rgba(0,0,0,0.05);
    }
    
    /* Custom Form Controls */
    .form-control {
        border-radius: 8px;
        border: 2px solid #e2e8f0;
        transition: all 0.3s ease;
    }
    
    .form-control:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.1);
    }
    
    /* Dark Mode Overrides */
    body.dark-mode .sidebar {
        background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
    }
    
    body.dark-mode .card {
        background: #2d3748;
        border-color: #4a5568;
    }
',

'custom_js' => '
    // Google Analytics
    gtag("config", "GA_MEASUREMENT_ID");
    
    // Toastr Configuration
    toastr.options = {
        positionClass: "toast-top-right",
        timeOut: 3000,
        progressBar: true,
        closeButton: true
    };
    
    // Custom Form Enhancements
    $(document).ready(function() {
        // Add focus effects to form controls
        $(".form-control").on("focus", function() {
            $(this).parent().addClass("focused");
        }).on("blur", function() {
            $(this).parent().removeClass("focused");
        });
        
        // Custom tooltips
        $("[data-toggle=\"tooltip\"]").tooltip();
        
        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            $(".alert").fadeOut("slow");
        }, 5000);
        
        // Real-time notifications
        if (typeof(EventSource) !== "undefined") {
            var source = new EventSource("/admin/notifications/stream");
            source.onmessage = function(event) {
                var data = JSON.parse(event.data);
                toastr.success(data.message);
            };
        }
        
        // Custom loading states
        $("form").on("submit", function() {
            var submitBtn = $(this).find("button[type=\"submit\"]");
            submitBtn.prop("disabled", true).html("<i class=\"fas fa-spinner fa-spin\"></i> Processing...");
        });
    });
    
    // Custom utility functions
    function showCustomModal(title, content) {
        $("#customModal .modal-title").text(title);
        $("#customModal .modal-body").html(content);
        $("#customModal").modal("show");
    }
    
    function refreshDashboard() {
        fetch("/admin/dashboard/data")
            .then(response => response.json())
            .then(data => {
                $("#total-users").text(data.users);
                $("#total-roles").text(data.roles);
                $("#total-permissions").text(data.permissions);
            });
    }
    
    // Auto-refresh every 30 seconds
    setInterval(refreshDashboard, 30000);
',

// Single permission
Route::get('/admin', [AdminController::class, 'index'])
    ->middleware('accesstree:add_permission');

// Multiple permissions (any)
Route::post('/articles', [ArticleController::class, 'store'])
    ->middleware('accesstree:create_articles,edit_articles');

// Role check
Route::delete('/articles/{id}', [ArticleController::class, 'destroy'])
    ->middleware('accesstree:role:admin');

use Obrainwave\AccessTree\Services\AccessTreeService;

$accessService = new AccessTreeService();

// Update role
$result = $accessService->updateAccess([
    'data_id' => 1,
    'name' => 'Senior Editor',
    'status' => 1
], 'Role', [1, 2, 3, 4, 5]);

// Delete permission
$result = $accessService->deleteAccess(1, 'Permission');

// Get all active permissions
$permissions = fetchActivePermissions();

// Get roles with pagination
$roles = fetchRoles([
    'paginate' => true,
    'per_page' => 15,
    'with_relation' => true,
    'order' => 'asc',
    'order_ref' => 'name'
]);

// Get specific role with permissions
$role = fetchRole(1);

// Get user's roles
$userRoles = fetchUserRoles($user->id);

// Get role permissions
$rolePermissions = fetchRolePermissions($roleId);

public function test_admin_can_access_dashboard()
{
    $user = User::factory()->create();
    AccessTree::assignRoles($user->id, ['Admin']); // or assign role id

    $this->actingAs($user)
         ->get('/admin')
         ->assertStatus(200);
}
bash
# 1) Require package
composer 
php artisan vendor:publish --tag="accesstree-migrations"
php artisan vendor:publish --tag="accesstree-config"

# 3) Migrate & seed (optional)
php artisan migrate
php artisan accesstree:seed

# 4) Install Admin Interface (Optional)
php artisan vendor:publish --tag="accesstree-admin-views"
php artisan vendor:publish --tag="accesstree-admin-routes"
bash
php artisan vendor:publish --tag="accesstree-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="accesstree-config"
bash
php artisan vendor:publish --tag="accesstree-seeders"
bash
 php artisan accesstree:seed
bash
# Publish admin views and routes
php artisan vendor:publish --tag="accesstree-admin-views"
php artisan vendor:publish --tag="accesstree-admin-routes"