Download the PHP package elpandape/warden without Composer

On this page you can find all versions of the php package elpandape/warden. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package warden

Warden

Warden

Roles & permissions for Laravel
Instance-level grants, explicit forbids, ownership, multi-tenancy, and ABAC.
Authorization that explains itself.

Packagist Version Total Downloads PHP 8.4+ Laravel 13+


๐Ÿ“– Table of Contents


โœจ Features

Feature Description
๐ŸŽฏ Laravel's Gate, zero learning curve can(), @can, authorize() โ€” works out of the box.
๐Ÿ”’ Explicit forbids A forbid() beats every grant. Distinguishes "denied" from "not granted."
๐Ÿ“Š whereCan() query scope The only package that can answer "over which rows?" as an Eloquent scope.
๐Ÿ” explain() debugging Know why a check resolved the way it did โ€” including "explicitly forbidden."
๐Ÿ—๏ธ ABAC constraints where('status', 'published') on grants โ€” evaluated on every check.
๐Ÿ  Ownership toOwn(Post::class) โ€” grant only what the user owns, resolved by attribute or closure.
๐ŸŽฏ Scoped roles assign('editor')->on($org) โ€” same role, different contexts.
โณ Temporary access until($moment) on a grant or an assignment โ€” it stops authorizing on its own.
๐Ÿช† Nested roles A role inside a role lends its grants, off by default and switchable live.
๐Ÿข Multi-tenancy Tenant-scoped rows with global fallback, injectable resolver, exception-safe onceTo().
๐Ÿ’พ Smart caching O(1) invalidation, versioned payloads, anti-stampede locking, Octane-safe.
๐Ÿ“ก Typed events Warden's verbs and catalog models announce exactly the rows they changed โ€” hydrated models (snapshots for what a deleted role held), end dates and contexts โ€” each stamped with the operation that wrote it.
๐Ÿ”ข Enum support BackedEnum accepted everywhere a name string is.
๐Ÿงช Testing helpers Warden::fake(), WithPermissions trait, artisan commands.
๐Ÿ”„ Migration path warden:upgrade + Rector set for silber/bouncer users.

๐Ÿ“‹ Requirements

Requirement Version
PHP ^8.4
Laravel ^13.0

๐Ÿš€ Installation

warden:install publishes the config, the migration, and runs it. You can also publish individually:

Then add the concern to your authority model(s):

๐Ÿ”„ Coming from silber/bouncer? This package conflicts with it by design (same default tables). Run php artisan warden:upgrade to migrate the schema in place. See MIGRATING-FROM-BOUNCER.md.

โฌ†๏ธ Already on warden 1.x? 2.0 adds a column and a unique index to permissions. Publish and run the upgrade migration โ€” vendor:publish --tag=warden-migrations-v2 then migrate โ€” before the first write. See UPGRADE.md.


โšก Quick Start


๐Ÿ” Checking Permissions

Nothing to learn โ€” it's Laravel's Gate.

Grant vs Check Matrix

Grant โ†“ / Check โ†’ can('edit') can('edit', Post::class) can('edit', $post)
to('edit') โœ… โ€” โ€”
to('edit', Post::class) โ€” โœ… โœ…
to('edit', $post) โ€” โ€” โœ… that one
to('edit', '*') โ€” โœ… โœ…
to('*') โœ… โ€” โ€”
toManage(Post::class) โ€” โœ… โœ…
everything() โœ… โœ… โœ…

๐Ÿ“Œ Rules:

  • forbid() beats every Warden grant.
  • By default, Warden answers after your policies โ€” policies always win.
  • Set warden.gate.run_before_policies to make forbids veto everything.
  • Checks with more than one argument are left to your policies.
  • Guests and non-model arguments are never answered by Warden.
  • Warden::can() inside a policy recurses through the Gate. Ask the resolver directly โ€” app(Contracts\Resolver::class) โ€” when a policy needs Warden's own answer.
  • With warden.gate.register off, Warden abstains from every Gate answer, so a loose permission with no policy behind it reads as denied by every route through the Gate โ€” $user->can(), Warden::can(), cannot(), canAny(), authorize() and the warden.permission middleware all go through the same Gate. What keeps answering is the resolver, app(Contracts\Resolver::class) โ€” and your policies, wherever you have one.

๐ŸŽ Granting & Forbidding

๐Ÿ“Œ An authority is a saved model with a usable key. allow(), forbid(), assign()->to() and sync() refuse one that is not saved โ€” a deleted one included โ€” or whose key is not an int or a non-empty string, with a ConfigurationException thrown before any row is written: the row would name nobody while the event named the model. disallow(), unforbid() and retract()->from() only need the key, so they keep working from a model's own deleted hook. When everyone is what you mean, say so with allowEveryone().

๐Ÿ“Œ Only allowEveryone() grants to everyone. Its rows carry neither an authority type nor a key, and those are the only rows can(), whereCan() and getPermissions() read as everyone's. A row with a type and no key โ€” 3.0.0 wrote one for an unsaved authority โ€” grants no saved model, and php artisan warden:clean --stranded deletes it.

๐Ÿ“Œ Assignments are one hop unless you turn nesting on. assign('auditor')->to($role) writes an edge between roles. By default holders of the outer role gain nothing from it โ€” set warden.roles.nested to true and they inherit the inner role's grants, to warden.roles.max_depth levels deep.

Off by default on purpose, because turning it on widens what every existing assignment reaches. The switch is read on every check rather than baked into a cached payload, so turning it back off takes effect immediately โ€” it is meant to work as an emergency lever. A cycle stops expanding at the depth ceiling instead of throwing.

can(), getPermissions(), getForbiddenPermissions() and every role check nest together โ€” isA() and its variants, isAll(), Warden::is(), whereIs(), whereIsAll(), whereIsNot() and the warden.role middleware: a split would let can('publish') say yes while Warden::is($user)->an('editor') says no, painting a menu wrong for precisely the users with the most access. The two listings count unrestricted assignments only, as they always have.

$role->nestedRoles() only reads the edges; Warden::assign($inner)->to($outer) and Warden::retract($inner)->from($outer) write them, scoped to the tenant, with the cache invalidated and the event fired. Every writer the relation declares โ€” attach(), detach(), sync(), toggle(), updateExistingPivot(), save(), create(), firstOrCreate() and the rest, OrFail and Quietly variants included โ€” throws a ConfigurationException pointing to those two, because a write through the relation would reach every tenant and context at once, with no invalidation and no event. So does the pivot on a loaded edge: $role->nestedRoles->first()->pivot refuses delete(), a save() that would change it, and the increment/decrement family.

$role->nestedRoles()->delete() deletes the inner roles themselves, as on any Eloquent relation โ€” it is not an unnest. It runs through the query builder, so no model event fires and the cache is not invalidated, and the foreign key takes every assignment of those roles with them.

Best Practices

โœ… Do โ€” use forbid() for exceptions:

โŒ Don't โ€” model exceptions with scattered conditionals; a forbid() row is queryable, auditable, and revocable:


โณ Temporary Access

Grants and role assignments can carry an end date. Past it they stop authorizing, stop appearing in whereCan(), and stop being listed by getPermissions() โ€” no command has to run for that to happen.

๐Ÿ“Œ The date lives on the assignment, not on the role. A role is a shared definition, so an end date there would end it for everyone. On the assignment, the same role can end on different days for different holders โ€” and when it does, the permissions that role lent go with it.

๐Ÿ“Œ An expired assignment stops counting as held, not only for can(). isA(), isAll(), Warden::is(), whereIs(), whereIsAll() and whereIsNot() read the date too, with nesting on or off, and so does the warden.role middleware, which answers an expired role with a 403. The relation is left alone: $user->roles still lists the row until something deletes it, with its date on the pivot's expires_at.

๐Ÿ“Œ until() goes before to(), like on(): writes execute immediately, so calling it afterwards throws rather than quietly doing nothing. Moving a date counts as a write โ€” it invalidates the cache and fires the same event as any other, whose entry carries the date before and after.

๐Ÿ“Œ A condition keeps the date. where() re-points a grant at its constrained twin (see Conditional Permissions), and the twin takes the date the same chain declared โ€” until(null) included, which lifts it. Without until() it keeps the date the grant already had; if the authority held that permission both plain and under a condition, with different dates, the later one wins and no end date beats any.

๐Ÿ“Œ Re-assigning does not revive an expired row. Saying nothing about time leaves the date alone, and that date has passed: assign('auditor')->to($user) or allow($user)->to('publish') over an expired row writes nothing, and the access stays ended. Give it a new date, or until(null) to make it permanent.

โš ๏ธ A forbid() cannot expire, and until() on one throws. A prohibition that lapsed by clock would turn a forbid beats every grant into until Tuesday, with the grant beneath it still live. Lift it deliberately with unforbid().

๐Ÿ“Œ A grant reached through a role outlives neither: the earlier of the two dates ends it.

๐Ÿ“Œ The boundary is exclusive. A row stops counting at the instant it names, not a tick later.

php artisan warden:clean --expired deletes rows past their date. It is hygiene, not part of the mechanism: an expired grant stops authorizing whether or not anyone runs it.


๐Ÿ  Ownership

Configure ownership resolution

๐Ÿ“Œ ownedVia() only registers; it never removes. ownedVia(Post::class, null) sets the global attribute to "App\Models\Post", which is never what you meant. Use notOwned() to take one class out, or 'default_attribute' => null in the config to turn the fallback off everywhere.

๐Ÿ“Œ A toOwn() grant against a class that resolves no ownership can never grant. The row is written and looks healthy; warden logs a warning so it is greppable.

Best Practices

โœ… Do โ€” let ownership carry the common case, forbid the exceptions:

โŒ Don't โ€” reimplement ownership inside policies you'll have to keep in sync.


๐ŸŽฏ Scoped Roles

Restrict a role to any model โ€” no global team_id required.

Configure membership resolution

๐Ÿ“Œ A restricted role's grants apply when the checked entity belongs to the context. Checks without an instance fail closed. Role membership checks (isAn('editor')) ignore restrictions by design โ€” but not end dates: an assignment past its until() stops counting, restricted or not.

Best Practices

โœ… Do โ€” model teams with the models you already have:

โŒ Don't โ€” fall back to one global role plus scattered if ($user->org_id === โ€ฆ) checks.


๐Ÿข Multi-tenancy

Behavior with no active tenant

Configure warden.scope.null_behavior:

๐Ÿ“Œ Writes always target one exact scope. A write under tenant 5 only affects tenant-5 rows. Global rules are only writable globally.

Reads and deletes are therefore asymmetric: a check under tenant 5 answers global or tenant 5, while retract() and disallow() delete tenant-5 rows only. So a retract under a tenant can succeed and leave the authority still holding the role globally. retract()->from() exposes retractedCount() for callers that need to tell the cases apart:

โš ๏ธ The scope rule is warden's, not Eloquent's. TenantScope filters reads and stamps creates; it does not isolate writes. $permission->delete() and $role->delete() reach rows in every tenant, and the foreign keys cascade below Eloquent entirely. Remove rows through warden's own verbs, or through warden:clean.

โš ๏ธ Pivot tenancy is a plain predicate, not a registered scope, so withoutGlobalScopes() does not lift it. Widen deliberately with Warden::tenant()->removeOnce(...), which is the supported escape hatch.

Under null_behavior => 'strict' it narrows instead. With no active tenant, strict reads only global rows, so removeOnce() turns (scope is null or scope = $tenant) into scope is null โ€” strictly fewer rows than the read it was meant to widen. Under the default 'all' it widens as described.

๐Ÿ“Œ Relation writes obey the rule too. detach(), sync(), toggle(), syncWithoutDetaching() and updateExistingPivot() on roles() and permissions() touch only rows at the active write scope, and attach() stamps it. A global row the tenant inherits stays out of reach in both directions: under tenant 5, sync([$role]) adds the tenant-5 row beside the global one instead of adopting it, and sync([]) leaves the global one standing. Relation writes invalidate the cache but announce nothing: see Events for auditing.

โš ๏ธ Scope, yes; restriction, no. A relation write narrows to one scope and stops there: it does not filter restricted_to_*, so $user->roles()->detach($editor) removes the scoped-role assignments along with the plain one. That mirrors Warden::retract('editor')->from($user) without ->on(), which deletes them all the same way โ€” the relation is not narrower than the verb it reflects. To remove one context and leave the others, name it: Warden::retract('editor')->on($org)->from($user).

โš ๏ธ A relation captures its write scope when it is built, not when it writes. $user->roles() resolves the active tenant at construction time, so a relation held in a property across a tenant change still writes to the scope it was born in. Ask for it again after switching tenants, or write through Warden::assign() / retract(), which resolve the scope per call โ€” and which also dispatch the typed events and report retractedCount().

๐Ÿ“Œ A role is global unless the write mints a tenant one. Under an active tenant, allow('editor') attaches to a global editor if one exists, rather than creating a tenant-scoped twin. Roles are looked up by name and scope; a tenant twin only exists once something writes it.

๐Ÿ“Œ The permission catalog behaves the same way, and in both halves a row the tenant minted for itself wins the global one it shadows. Under a tenant, allow($user)->to('publish') reuses a global publish row when that is all there is, and picks the tenant's own the moment one exists. Set Warden::tenant()->onlyRelations() to keep the catalog global on purpose.

๐Ÿ“Œ Tenancy::writeScope() takes forRoleGrant, and it defaults to false. A bare call therefore reports the scope of an authority grant; ask with forRoleGrant: true when the holder is a role, or the answer describes a different write than the one you meant.

Best Practices

โœ… Do โ€” remove a global forbid where it lives: outside any tenant:

โŒ Don't โ€” expect a tenant-scoped unforbid() to lift a global forbid.


๐Ÿ”ง Conditional Permissions (ABAC)

Grants can carry conditions, written in the grammar your queries already use:

Available operators

Method Description
where('col', 'value') Entity attribute equals value
where('col', '>=', 5) With explicit operator
whereColumn('owner_id', 'id') Compare against authority's attribute
orWhere(...) OR grouping
orWhere(fn) Nested closure grouping

๐Ÿ“Œ Important:

  • Precedence is SQL's: AND binds tighter than OR.
  • Comparisons are strict โ€” no PHP type juggling.
  • A null attribute satisfies no operator at all, != included, and values whose types are not decidably comparable fail closed the same way. A missing attribute is different: under Model::preventAccessingMissingAttributes() it throws rather than failing closed.
  • Constrained grants share one catalog row per distinct rule, so editing a permission's options changes the rule for every holder of that shape. Write a new condition instead of editing a shared row.
  • A boolean value matches only a column the model casts to bool, and such a column matches only a boolean, so writing either mismatch is refused: where('classified', true) needs 'classified' => 'bool' in the model's $casts. A row stored before 3.0 keeps failing closed in checks and in queries alike โ€” php artisan warden:doctor lists those rows.
  • The refusal exists because of what the mismatch does to a forbid(): a condition that can never be true makes the prohibition inert, the grant underneath it stays live, and explain() reports that grant without ever mentioning the forbid โ€” a missing cast read as "allowed".
  • A permission with no entity is only ever checked without an instance, so constraining one is refused: the shape that would make it match is the shape that rejects it.
  • A constrained grant never matches instance-less checks (can('view'), can('view', Document::class)) โ€” they fail closed.
  • to()->where() is two writes, not one. to() lands an unconstrained grant that authorises every instance, and where() re-points it at the constrained twin. Only the second step runs in a transaction; between the two the live row is unconditional, and a throw in where() โ€” an unknown operator, a permission with no entity, a twin in the trash (TrashedCatalogRow) โ€” leaves it that way. Wrap the whole chain in your own transaction when that window matters.

Best Practices

โœ… Do โ€” grant broadly, constrain the sensitive part:

โŒ Don't โ€” encode workflow logic as constraints (e.g., "drafts visible on Tuesdays"). Complex rules belong in policies.


๐Ÿ“Š Querying by Permission

Checks answer "can X do Y?"; Warden can also answer "over which rows?"

Instance grants, class grants, wildcards, everyone-grants, role grants, forbids, tenancy, ownership, and ABAC constraints all compile into the query.

โš ๏ธ What cannot become SQL fails closed: closure-resolved ownership and restricted-role grants contribute no rows.

โš ๏ธ No Gate, no policies. whereCan() answers from warden's own rows only. A policy that would have granted or denied a row is not consulted, so a query and a check can disagree wherever a policy has the last word.

โš ๏ธ The trait is required. Without it, Post::whereCan($user, 'view') never reaches Warden: Laravel reads it as a dynamic where against a column named can, and you get zero rows or a driver error instead of an answer.

Best Practices

โœ… Do โ€” drive index pages straight from authorization:

โŒ Don't โ€” post-filter with ->get()->filter(fn ($p) => $user->can('view', $p)) โ€” that's the N+1 this scope exists to delete.


๐Ÿ” Debugging with explain()

Which of permission and role are populated depends on the cause:

Cause allowed() permission role
GrantedDirectly true the row โ€”
GrantedViaRole true the row the role
GrantedToEveryone true the row โ€”
ForbiddenDirectly false the row โ€”
ForbiddenViaRole false the row the role
ForbiddenToEveryone false the row โ€”
ConditionsNotMet false the row whose conditions were not satisfied โ€”
NoMatchingGrant false โ€” โ€”
NotApplicable false โ€” โ€”

๐Ÿ“Œ ConditionsNotMet and NoMatchingGrant are different answers: the first names a row that matched the shape but whose conditions were not satisfied โ€” they failed against the instance, or the check named a class and there was no instance to satisfy them with โ€” while the second means nothing matched at all. Both leave Warden abstaining so your policies decide.

๐Ÿ“Œ Always answered by the database engine โ€” never from cache โ€” so it diagnoses stale-cache issues too.

๐Ÿ“Œ It blames the row that decided, and the role that holds it. A row past its end date is never blamed, and neither is a role in the trash: explain() looks past both to the next source. With warden.roles.nested on, a row held by a role nested inside one the authority holds is GrantedViaRole or ForbiddenViaRole, and role names the nested role โ€” or the authority's own role, when that one holds the row too. When several roles hold the row, role names the first one the check counted, the roles the authority holds before those nested inside them โ€” so a role it holds under a restriction that does not apply, and also reaches through another role it holds, can be named ahead of that other role.


๐Ÿ“ก Events

Warden announces its own writes. Every verb โ€” allow(), forbid(), disallow(), unforbid(), assign(), retract(), sync(), and the where() that narrows a grant โ€” dispatches a typed, readonly event, and so does creating, editing, deleting or restoring a role or permission through its model. Each event names what it touched with hydrated models (never raw IDs; what a deleted role held arrives as Events for auditing says which, and when each event is dispatched. Disable globally with warden.events_enabled.

Event Fired By Payload
PermissionGranted / PermissionForbidden allow(), forbid(), and the where() that narrows them ?Model $authority, Collection $permissions, $scope, ?Model $actor, list<GrantChange> $grants
PermissionRevoked / PermissionUnforbidden disallow(), unforbid(), a narrowing where(), deleting a permission ?Model $authority, Collection $permissions, $scope, ?Model $actor, list<GrantRemoval> $grants
RoleAssigned assign() Model $authority, Collection $roles, $scope, ?Model $restrictedTo, ?Model $actor, list<AssignmentChange> $assignments
RoleRetracted retract(), deleting a role Model $authority, Collection $roles, $scope, ?Model $restrictedTo, ?Model $actor, list<AssignmentRemoval> $assignments
RolesSynced / PermissionsSynced sync() Model $authority, SyncResult $changes (attached / detached / kept), $scope, ?Model $actor; PermissionsSynced adds bool $forbidden
RoleCreated / PermissionCreated Creating the row โ€” also when a verb names one that does not exist yet The model, ?Model $actor
RoleUpdated / PermissionUpdated A model save that changes the row's snapshot The model, array $before, array $after, list<string> $changed, ?Model $actor
RoleDeleted Deleting the role through its model โ€” to the trash too Model $role, ?Model $actor, array $heldGrants, array $heldRoles, bool $softDeleted
PermissionDeleted Deleting the permission through its model โ€” to the trash too Model $permission, ?Model $actor, bool $softDeleted
RoleRestored / PermissionRestored restore() on a row in the trash, through its model The model, ?Model $actor

๐Ÿ“Œ Every event ends with ?string $operation โ€” these sixteen and the six Event::defer() a forceDelete() says true too: trust the flag only for deletes made outside it.

The six write events carry one value per pivot row they wrote or deleted โ€” $grants on the permission events, $assignments on the role events:

Value On Properties
GrantChange PermissionGranted, PermissionForbidden Model $permission, bool $created, ?CarbonImmutable $expiresAt, ?CarbonImmutable $previousExpiresAt
AssignmentChange RoleAssigned Model $role, bool $created, ?CarbonImmutable $expiresAt, ?CarbonImmutable $previousExpiresAt
GrantRemoval PermissionRevoked, PermissionUnforbidden Model $permission, ?CarbonImmutable $expiresAt โ€” the date the row had when it went
AssignmentRemoval RoleRetracted Model $role, ?Model $restrictedTo โ€” the row's own context โ€” and ?CarbonImmutable $expiresAt

A write reads like this:

The row created expiresAt previousExpiresAt
Was just created true the date it was created with, or null null
Had its date moved false the new date the old date
Got its first date false the new date null
Had its date lifted with until(null) false null the old date

๐Ÿ“Œ With created: false the two dates always differ โ€” a write that moves nothing is not announced. expiresAt is read back from the row, so it is the wall time the column stores, in your application's timezone, rather than the object you passed to until().

๐Ÿ“Œ PermissionForbidden carries $grants too. A forbid cannot take until(), so in practice its entries are new rows with no end date.

๐Ÿ“Œ Building an event yourself โ€” in a test, say? Pass its arguments by name from actor on. Warden only ever appends optional parameters, so a name stays valid where a position would not.

$actor defaults to the authenticated user, on every post-write event โ€” the catalog's included โ€” and warden resolves it only for an event that goes out: never with events off, nor for the writes a sync() silences. Queues, console commands and impersonation are cases only your application can answer, so point warden.actor_resolver at a class implementing Contracts\ActorResolver:

Pre-action events (opt-in)

Enable with warden.cancellable_events. A listener returning false aborts the write:

๐Ÿ“Œ A pre-action event covers the whole call, not one item of it. allow($user)->to(['a', 'b']) announces both names in one event, and a listener returning false aborts both: there is no way to veto one and keep the other. Split the call if you need per-item decisions.

๐Ÿ“Œ sync() never fires nor honors pre-action events โ€” its declarative diff events tell the whole story.

๐Ÿ“Œ where() fires none. It refines the grant to() has just made, and to() fired its own.

๐Ÿ“Œ A cascade fires none either. Deleting a role never fires RetractingRole, nor deleting a permission RevokingPermission: the foreign key deletes inside the engine, and the only veto over the delete is Eloquent's own โ€” return false from a deleting listener on the model.

๐Ÿ“Œ Event::defer() defeats the veto. A pre-action event dispatched inside it reaches its listeners only after the write it announces, so a false stops nothing: see When an event is dispatched.

Events for auditing

What an audit log built on these events can rely on, and what it cannot.

What an event describes

An event describes rows warden wrote or deleted at $scope โ€” not the access that results. Ask Warden::explain() about access. So:

What a write announces

One call, one operation

Every event carries $operation, the id of the operation that dispatched it, so a log can show what one act wrote as one entry. It is a ULID โ€” 26 upper-case characters, ordered by the time the operation opened โ€” and it only says which events belong together.

The PermissionRevoked and the PermissionForbidden of the flipped cell, and the PermissionGranted of the other two, carry the same $operation: a log can show the flip as one change instead of two. operation() returns what its callback returns. There is no accessor for the id of an open operation: take it from the callback's argument, or from an event.

Implicit creation and the narrowing chain

Sync

Deleting a role or a permission

Maintenance commands

Editing the catalog

Writes that announce nothing

Testing with Event::fake()

Event::fake() with no list replaces the dispatcher Eloquent's model events go through, so warden's model hooks stop running with it: identity keys, generated titles, the tenant stamp, the catalog events, cache invalidation, and a delete's sweep and cascade. In a test suite it shows up as a unique-constraint violation on the second permission of a name, as a permission created global under a tenant, or as an Event::assertDispatched(PermissionCreated::class) that fails because the hook that dispatches it never ran. Fake warden's events by name instead:

Add the pre-action events you assert on โ€” AssigningRole, RetractingRole, GrantingPermission, ForbiddingPermission, RevokingPermission, UnforbiddingPermission โ€” the same way. A faked pre-action event never vetoes.

Queued listeners

A queued listener receives the event serialized, and its values come back in two ways:

RoleDeleted and PermissionDeleted differ on both counts. The deleted row travels by value, without the relations it had loaded, so the listener gets it as it was when it went, with $softDeleted and $operation. The actor travels as an identifier and is read again when the job runs; if its row is gone by then, it arrives as an unsaved stand-in carrying only its key, on the connection the actor came from (exists is false), instead of failing the job.

A queued listener therefore always knows which operation dispatched its event. What its own warden writes join depends on the queue driver: see One call, one operation.

โš ๏ธ A model that travels by value keeps every column, $hidden included โ€” $hidden only shapes arrays and JSON. The deleted row of RoleDeleted and PermissionDeleted is one, as are the roles and permissions in the lists, the entries and a sync's $changes, and the context an AssignmentRemoval names. If your own models (warden.models.*, or a context model) hold a sensitive column, make the queued listeners of any warden event that carries them implement ShouldBeEncrypted. None of them takes its loaded relations along: each travels as a copy without them โ€” one copy per model and event, so after the queue $event->roles[0] === $event->assignments[0]->role still holds โ€” and a queued listener that walks one loads it again, which under Model::preventLazyLoading() can throw. A synchronous listener gets your instances as you had them, relations and all, with two exceptions: the context you hand to on() and the deleted role a cascade names reach it as copies too, so an entry's context is neither the instance you handed to on() nor === $event->restrictedTo, which stays yours, relations and all, and a cascade's role is not the model you called delete() on. Walk a relation from $event->restrictedTo: under Model::preventLazyLoading(), loading one from the copy can throw.

When an event is dispatched

Waiting for the commit

Warden dispatches synchronously on purpose: a listener that writes its audit row in the same transaction, or that vetoes a write by throwing, depends on it. When a listener should only hear about committed changes, Laravel lets that listener class wait:

A queued listener implements ShouldQueueAfterCommit instead. Know the limits:

Snapshots

A snapshot names a role or a permission as it was, as a plain array whose shape is frozen. RoleUpdated and PermissionUpdated carry one from before the edit and one from after, RoleDeleted one for each row the role held, and you can take your own:

The twin that Warden::allow($user)->to('view', Document::class)->where('status', 'published') writes reads:

and a role reads ['v' => 1, 'key' => 3, 'name' => 'editor', 'title' => 'Editor', 'scope' => null].

โš ๏ธ snapshot() on a model comes from warden's trait, and in PHP a trait method wins over one inherited from a parent class. If your role or permission model extends a base class that already defines snapshot(), the trait's hides it โ€” and if the two signatures are incompatible, PHP refuses to load the model class. Warden itself always calls the Support\Snapshots classes.


โš ๏ธ Exceptions

All typed, all catchable the Laravel way:

Exception Extends Notes
RoleDoesNotExist ModelNotFoundException โ€”
PermissionDoesNotExist ModelNotFoundException โ€”
UnauthorizedException AuthorizationException getRequiredPermissions() / getRequiredRoles()
ConfigurationException โ€” Fail-fast on bad config
TrashedCatalogRow ConfigurationException A name matches only a role or permission in the trash: restore it or force-delete it first

๐Ÿ“Œ UnauthorizedException messages are translatable (shipped in English and Spanish). Displaying the missing permission/role name in the message is opt-in via warden.exceptions.display_*.


๐Ÿ”ข Enums

Every public signature that takes a permission or role name also accepts a string-backed enum:


๐Ÿ’พ Caching

Enabled by default. One minimal payload per authority, O(1) automatic invalidation, anti-stampede locking, Octane-safe.

Manual invalidation

Best Practices

โœ… Do โ€” write through Warden and let invalidation take care of itself:

โŒ Don't โ€” raw database edits (seeders, manual SQL) bypass invalidation. After hand-editing rows, call Warden::refresh() โ€” or better, make the edit through the API.

๐Ÿ“Œ "Through the API" includes the models. Editing a Grant, an AssignedRole or a catalog row through Eloquent invalidates too โ€” renaming a permission or rewriting its options reaches every cached check, in every tenant its grants live in, because a permission's own columns are baked into the payload. Moving a row's scope that way invalidates the tenant it left as well as the one it joined, and moving a role or a permission in or out of the trash invalidates every scope it reaches โ€” less when a deleting listener of yours halts the dispatch: see Deleting a role or a permission. What still needs Warden::refresh() is a write that fires no model event: the query builder (a query's delete() and restore() on a SoftDeletes model included), DB::table(), a raw statement, and a model write with its events off โ€” saveQuietly(), deleteQuietly(), restoreQuietly(), Model::withoutEvents(), or a bare Event::fake() in a test.

โš ๏ธ The in-memory matcher compares permission names byte-exactly, while a case-insensitive database collation may match Edit to edit. Use exact, consistent names.


๐Ÿงช Testing

Fake mode

A scripted rule answers for every authority unless you narrow it. Each verb below narrows the rule scripted just before it, so they chain:

Ownership, conditions and tenancy are decided by the same pieces the database engine uses, and a test suite asserts the fake and the engine answer alike across the shapes a rule can take. Narrowing before scripting a rule throws.

๐Ÿ“Œ The fake is not looser than the engine. A rule with no entity answers entity-less checks only, a condition abstains where it has no instance to read, and an unscripted check abstains so your app's policies still decide. Where the fake cannot express something, it denies rather than granting.

โš ๏ธ Warden::fake() is not Event::fake(). A bare Event::fake() also stops the model hooks warden depends on โ€” identity keys, titles, cache invalidation. Fake warden's events by name instead: the list is under Events.

WithPermissions trait

Artisan commands

๐Ÿ“Œ warden:doctor exits non-zero when it finds something, so it works as a CI gate. It reads every stored condition back through the rule the write path enforces and reports the ones that would be refused today, with the permission and how many grants and forbids point at it. It changes nothing: adding the missing cast and rewriting the condition mean different things, and only you know which one you meant.


๐Ÿ›ก๏ธ Middleware & Blade

Off by default. Enable via config:

Middleware

๐Ÿ“Œ warden.role answers exactly like isA(). An assignment past its end date does not count, and with warden.roles.nested on, a role reached through another one does. A denial throws UnauthorizedException, which Laravel renders as a 403.

Blade


๐Ÿ—๏ธ Schema & Models

Four tables:

Table Purpose
permissions The catalog
roles Role definitions
assigned_roles Role โ†” authority pivot
grants Permission โ†” authority (with forbidden flag)

๐Ÿ“Œ Revoking removes the grant, never the catalog row. The row is shared, so pruning it inline would destroy a rule other holders point at. warden:clean is the supported way to reclaim rows nothing points at, and --duplicates collapses rows that identify the same permission. When a grant it re-points collides with one the surviving row already holds, the survivor keeps the later end date โ€” no end date beats any.

๐Ÿ“Œ Both pivot relations mix granted and forbidden rows. $role->permissions() and $permission->roles() return every pivot row, whichever polarity it carries โ€” filter to read one side:

๐Ÿ“Œ Load the whole permission row before changing what identifies it. entity_type, entity_id, only_owned, scope and options make up its identity key, so changing any of them on a permission fetched with a partial select() throws a ConfigurationException instead of saving a key computed from half a row. A permission created in the same request counts as whole: what it left unset holds the column default. An edit that leaves those five alone โ€” its title, say โ€” still saves, in strict mode too, and a save never moves an existing row into the active tenant: the tenant is stamped on creation only.

๐Ÿ“Œ Titles are generated once, on creation, and only when none was given. A rename keeps the old title, and setting title to null on an update leaves it null. Recompute one deliberately with Support\Titles\PermissionTitle::generate() or RoleTitle::generate() โ€” the same calls the hook makes.

๐Ÿ“Œ Ask before you rewrite a title. PermissionTitle::generations() and RoleTitle::generations() return every title Warden could have written for a name, current first โ€” each generator this package has published is transcribed and frozen. A stored title inside that list was Warden's; one outside it was typed by a person and is not yours to overwrite.

php artisan warden:retitle applies exactly that rule across the catalogue: a title an older Warden generated converges on the current wording, a title someone wrote stays, and a null stays null. Run it with --dry-run first.

Any model can hold roles and permissions:

Swap models via config

๐Ÿ“Œ Never hardcode package classes in relations. Always resolve via config.

๐Ÿ“Œ The grant or assignment a verb creates is inserted unguarded. Warden creates the row with its end date in a single INSERT, inside Model::unguarded() โ€” as Laravel's forceCreate() does โ€” so no $fillable or $guarded on your grant or assignment model can split it into an insert and a later update. That covers allow() and forbid() with to() or toOwn() โ€” and everything(), toManage() and toOwnEverything(), which go through them โ€” the grant a where(), orWhere(), whereColumn() or orWhereColumn() moves onto its constrained twin, and assign()->to(), sync()->roles() included. The switch is global while Warden looks the row up and, if it is missing, inserts it: an observer or listener that runs in that window โ€” your pivot model's retrieved, saving, creating, created or saved โ€” fills any model without mass-assignment protection, and retrieved runs unguarded even when the row is already there and nothing is inserted, as on a second allow()->to() of the same grant, a re-date, or a sync() that keeps it. A grant that sync()->permissions() or sync()->forbiddenPermissions() creates carries no end date, and is inserted as before, through your model's mass-assignment rules.


โš™๏ธ Configuration

Everything lives in config/warden.php:

Section Controls
models Swappable Role, Permission, Grant, AssignedRole models
tables Table names and database connection
morphs Morph aliases (warden.role, warden.permission)
gate Gate behavior (run_before_policies, register)
ownership Global/per-class ownership attribute
scope Multi-tenancy semantics
cache Store, prefix, TTL
events Enable/disable events, cancellable pre-action events
exceptions Display permission/role names in messages

๐Ÿ“– Recipes

Authorize someone other than the current user

Ownership through a pivot table

โš ๏ธ Closure-resolved ownership cannot compile into whereCan().

Default role for new users

๐Ÿ’ก There is no "role for everyone" by design. Use Warden::allowEveryone()->to(...) for global grants.

Landlord vs tenant databases

Point warden tables at their own connection with warden.connection. The published migration honors it (Schema::connection(...)), and the migration class is anonymous to avoid collisions. warden:clean --stranded follows the split: when an authority model lives on another connection, it looks for that authority's rows there rather than on warden's. It asks the connection the authority model resolves while the command runs, so it assumes one users database: with one per tenant, every other tenant's holders would look gone, so do not run --stranded in that layout.

Replace a role instead of stacking

Long-lived processes (Tinker, Octane, queues)

Writes through the API invalidate caches automatically. What still needs Warden::refresh() is a write that fires no model event โ€” the query builder, DB::table(), a raw statement, or a model write with its events off: see operation live in container-scoped bindings, so Octane requests and queue jobs reset themselves; the sync queue driver runs a job inside the request that queued it, and shares both โ€” unless the listener waits for the commit (ShouldQueueAfterCommit, $afterCommit = true, or a connection with after_commit), in which case it runs after, with its own operation.


๐Ÿ”„ Migrating from silber/bouncer

The fluent API is intentionally compatible. The schema upgrades in place (abilities โ†’ permissions, permissions pivot โ†’ grants). See MIGRATING-FROM-BOUNCER.md for the full equivalence table.


๐Ÿงช Development

No local PHP or Composer needed โ€” everything runs through Docker:


๐Ÿ‘ค Credits & License

Licensed under the MIT License.


Authorization that explains itself.


All versions of warden with dependencies

PHP Build Version
Package Version
Requires php Version ^8.4
illuminate/auth Version ^13.0
illuminate/contracts Version ^13.0
illuminate/database Version ^13.0
symfony/uid Version ^7.4 || ^8.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package elpandape/warden contains the following files

Loading the files please wait ...