PHP code example of elpandape / warden

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

    

elpandape / warden example snippets


use ElPandaPe\Warden\Concerns\HasRolesAndPermissions;

class User extends Authenticatable
{
    use HasRolesAndPermissions;
}

use ElPandaPe\Warden\Facades\Warden;

// Grant
Warden::allow($user)->to('edit', Post::class);

// Forbid (always wins)
Warden::forbid($user)->to('edit', $secretPost);

// Scoped role
Warden::assign('editor')->on($org)->to($user);

// Check
$user->can('edit', $post);                          // Laravel's Gate
Post::whereCan($user, 'edit')->paginate();           // Which rows?
Warden::explain($user, 'edit', $post);               // Why?

$user->can('edit-site');            // simple permission
$user->can('edit', $post);          // one instance
$user->can('edit', Post::class);    // the whole class
Gate::authorize('edit', $post);     // throws on deny
@can('edit', $post) ... @endcan     // Blade, as always

use ElPandaPe\Warden\Facades\Warden;

// Simple permission
Warden::allow($user)->to('ban-users');

// Class-level
Warden::allow($user)->to('edit', Post::class);

// Instance-level
Warden::allow($user)->to('edit', $post);

// Wildcard
Warden::allow($user)->everything();

// Everyone
Warden::allowEveryone()->to('browse');

// Roles
Warden::assign('admin')->to($user);
Warden::allow('admin')->to('audit');

// Declarative sync
Warden::sync($user)->roles(['editor', 'writer']);

> // config/warden.php
> 'roles' => ['nested' => true, 'max_depth' => 10],
> 

Warden::allow($user)->to('view', Document::class);
Warden::forbid($user)->to('view', $classifiedDocument);

Warden::unforbid($user)->to('view', $classifiedDocument);

use ElPandaPe\Warden\Facades\Warden;

Warden::allow($user)->until(now()->addDays(7))->to('publish', Post::class);
Warden::assign('auditor')->until($audit->ends_at)->to($user);

// Lift an end date a previous write left; saying nothing leaves it alone.
Warden::allow($user)->until(null)->to('publish', Post::class);

// All actions on owned posts
Warden::allow($user)->toOwn(Post::class);

// Only specific actions
Warden::allow($user)->toOwn(Post::class, ['edit']);

// Everything owned
Warden::allow($user)->toOwnEverything();

// Global attribute
Warden::ownedVia('author_id');

// Per class
Warden::ownedVia(Post::class, 'writer_id');

// Closure (evaluated live, never cached)
Warden::ownedVia(fn ($post, $user) => $post->team_id === $user->team_id);

// This class has no owner at all — overrides the global fallback
Warden::notOwned(Setting::class);

Warden::allow($user)->toOwn(Post::class);
Warden::forbid($user)->toOwn(Post::class, 'delete'); // owners still can't delete

Warden::assign('editor')->on($orgOne)->to($user);   // editor only inside orgOne
Warden::assign('editor')->on($orgTwo)->to($user);   // same role, second context
Warden::retract('editor')->on($orgOne)->from($user); // leave one; without on(), all

Warden::restrictedVia(Post::class, 'organization_id');  // membership by FK
Warden::restrictedVia(fn ($entity, $context) => ...); // or a closure

Warden::assign('admin')->on($project)->to($user);
$user->can('manage', $project);          // true: the entity IS the context
$user->can('edit', $taskInProject);      // true: task->project_id points at it

Warden::tenant()->to($tenantId);                    // scope everything to this tenant
Warden::tenant()->onceTo(9, fn () => ...);         // temporary, exception-safe
Warden::tenant()->onlyRelations();                  // keep permission catalog global
Warden::tenant()->dontScopeRoleGrants();

$removed = Warden::retract('editor')->from($user)->retractedCount();  // rows deleted at this scope

Warden::tenant()->removeOnce(fn () => Warden::unforbid($user)->to('publish'));

Warden::allow($user)->to('view', Document::class)
    ->where('status', 'published')
    ->orWhere(fn ($group) => $group
        ->where('tier', '>=', 2)
        ->whereColumn('owner_id', 'id')
    );

Warden::allow('viewer')->to('view', Document::class)->where('status', 'published');
Warden::forbid($user)->to('view', Document::class)->where('classified', true);

use ElPandaPe\Warden\Concerns\QueriesByPermission;

class Post extends Model
{
    use QueriesByPermission;
}

// Usage
Post::whereCan($user, 'view')->latest()->paginate();

Post::whereCan($user, 'view')->latest()->paginate();

$why = Warden::explain($user, 'edit', $post);

$why->allowed();      // bool
$why->cause;          // Cause::ForbiddenViaRole, Cause::GrantedDirectly, …
$why->permission;     // the decisive catalog row, when one decided
$why->role;           // the role that carried it, when one did
(string) $why;        // "Explicitly forbidden by permission [edit] via role [banned]."

use ElPandaPe\Warden\Events\PermissionGranted;

Event::listen(PermissionGranted::class, function (PermissionGranted $event) {
    foreach ($event->grants as $grant) {
        // $authority received it; $actor granted it.
        audit(
            $grant->created ? 'granted' : 'date changed',
            $event->actor,
            $event->authority,
            $grant->permission->getAttribute('name'),
            $grant->expiresAt,
        );
    }
});

final class CurrentActor implements ActorResolver
{
    public function resolve(): ?Model
    {
        return Context::actingUser() ?? Auth::user();
    }
}

// GrantingPermission, ForbiddingPermission, AssigningRole
// RevokingPermission, UnforbiddingPermission, RetractingRole

use ElPandaPe\Warden\Facades\Warden;

// Saving a permission grid: 'delete' flips from granted to forbidden; 'view' and 'edit' are granted.
$operation = Warden::operation(function (string $operation) use ($role) {
    Warden::disallow($role)->to('delete', Document::class);
    Warden::forbid($role)->to('delete', Document::class);
    Warden::allow($role)->to(['view', 'edit'], Document::class);

    return $operation;
});

use ElPandaPe\Warden\Events;
use Illuminate\Support\Facades\Event;

Event::fake([
    Events\PermissionGranted::class, Events\PermissionForbidden::class,
    Events\PermissionRevoked::class, Events\PermissionUnforbidden::class,
    Events\RoleAssigned::class, Events\RoleRetracted::class,
    Events\RolesSynced::class, Events\PermissionsSynced::class,
    Events\RoleCreated::class, Events\RoleUpdated::class, Events\RoleDeleted::class, Events\RoleRestored::class,
    Events\PermissionCreated::class, Events\PermissionUpdated::class, Events\PermissionDeleted::class,
    Events\PermissionRestored::class,
]);

use ElPandaPe\Warden\Events\PermissionGranted;
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;

final class RecordGrant implements ShouldHandleEventsAfterCommit
{
    public function handle(PermissionGranted $event): void
    {
        // Runs once the open transaction commits; never if it rolls back.
    }
}

use ElPandaPe\Warden\Support\Snapshots\PermissionSnapshot;
use ElPandaPe\Warden\Support\Snapshots\RoleSnapshot;

PermissionSnapshot::of($permission);   // or $permission->snapshot()
RoleSnapshot::of($role);               // or $role->snapshot()

[
    'v' => 1,
    'key' => 12,
    'name' => 'view',
    'title' => 'View documents',
    'entity_type' => 'App\Models\Document',
    'entity_id' => null,
    'only_owned' => false,
    'scope' => null,
    'conditions' => [
        'g' => ['i' => [['and', ['c' => 'status', 'o' => '=', 't' => 'value', 'v' => 'published']]], 't' => 'group'],
        'v' => 1,
    ],
]

Warden::findRole('ghost');            // RoleDoesNotExist (ModelNotFoundException)
Warden::findPermission('ghost');      // PermissionDoesNotExist
Warden::authorize('publish', $post);  // UnauthorizedException (AuthorizationException)

enum Permission: string
{
    case EditSite = 'edit-site';
}

enum Role: string
{
    case Admin = 'admin';
}

Warden::allow($user)->to(Permission::EditSite);
Warden::assign(Role::Admin)->to($user);
$user->isAn(Role::Admin);
Warden::authorize(Permission::EditSite);

// config/warden.php
'cache' => [
    'enabled' => true,
    'store' => 'default',
    'prefix' => 'warden',
    'expiration_time' => DateInterval::createFromDateString('24 hours'),
],

Warden::refresh();          // O(1) version bump — invalidates everything
Warden::refreshFor($user);  // Drop one authority's payload

Warden::disallow($user)->to('publish');   // next check is already correct

$fake = Warden::fake();
$fake->allow('edit-site')->forbid('delete');

$fake->assertChecked('edit-site');
$fake->assertGranted('edit-site');
$fake->assertForbidden('delete');
$fake->assertNothingChecked();

$fake->allow('publish')->for($editor);                  // this authority only
$fake->allow('edit', Post::class)->owned();             // only what they own
$fake->allow('edit', Post::class)->where('status', 'draft');
$fake->allow('edit', Post::class)->whereColumn('author_id', 'id');
$fake->allow('publish')->inScope(5);                    // only inside tenant 5
$fake->allow('*', '*');                                 // everything, everywhere

use ElPandaPe\Warden\Testing\WithPermissions;

$this->allowUser($user, 'view', Document::class);
$this->assignRoles($user, 'admin');

'warden.register_middleware_aliases' => true,
'warden.register_blade_directives' => true,

Route::get('/admin', ...)->middleware('warden.role:admin,editor');      // any of
Route::put('/site', ...)->middleware('warden.permission:edit-site');    // all of

> $role->permissions()->wherePivot('forbidden', false)->get();   // what it can do
> $role->permissions()->wherePivot('forbidden', true)->get();    // what it is denied
> 

> PermissionTitle::generations('viewAny', Post::class, null, false);
> // ['View any posts', 'ViewAny posts']  ← current, then the pre-2.0 reading
> 

use ElPandaPe\Warden\Concerns\HasRolesAndPermissions;

class User extends Authenticatable
{
    use HasRolesAndPermissions;
}

// config/warden.php
'models' => [
    'role' => App\Models\Role::class,
],

// app/Models/Role.php
class Role extends Model
{
    use ElPandaPe\Warden\Models\Concerns\IsRole;
}

Gate::forUser($tenantUser)->allows('edit', $post);
Warden::explain($tenantUser, 'edit', $post);

Warden::ownedVia(Business::class, fn ($business, $user) =>
    $business->owners()->whereKey($user->getKey())->exists()
);
Warden::allow($user)->toOwn(Business::class, ['manage']);

// In your User model or observer:
protected static function booted(): void
{
    static::created(fn (User $user) => Warden::assign('member')->to($user));
}

Warden::sync($user)->roles(['editor']);     // declarative
Warden::retract('viewer')->from($user);       // or surgical
Warden::assign('editor')->to($user);
bash
php artisan vendor:publish --tag=warden-config
php artisan vendor:publish --tag=warden-migrations
bash
php artisan warden:show [Class:id]       # Show permissions for an authority
php artisan warden:cache-reset           # Reset cache
php artisan warden:clean --dry-run       # Clean orphaned permissions
php artisan warden:retitle --dry-run     # Converge titles an older Warden wrote
php artisan warden:doctor                # Audit the catalog for rules that can never be true