Download the PHP package happenv-com/laravel-access-control without Composer

On this page you can find all versions of the php package happenv-com/laravel-access-control. 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 laravel-access-control

Laravel Access Control

![Laravel Access Control](art/banner.png)

Latest Version Tests PHPStan Quality Total Downloads

A modular access control library for Laravel applications that uses enum-based permissions and a voter system. Perfect for modular monolith architectures where different modules can define their own permission logic and extend existing.

Example

Imagine two modules: Product and ProductGallery. The Product module knows nothing about ProductGallery, but ProductGallery should block product deletion until all galleries are removed.

Product module defines the permission:

ProductGallery module registers a voter to add its constraint:

This library allows achieving such behavior without tightly coupling the two modules.

Key Features

When to Use This Package

This package is designed primarily for modular monolith architectures where your application is split into independent modules (e.g., using nWidart/laravel-modules or InterNACHI/modular).

The key advantage of this package is that voters can be registered from any module, allowing each module to define its own authorization constraints without modifying the core application or other modules.

When NOT to Use This Package

If you're building a traditional Laravel monolith without modular architecture, you probably don't need this package. In that case, the following solutions are sufficient:

Filament

Building a Filament panel? happenv-com/filament-access-control puts this library on screen with nothing but Filament's own components. Its access control page shows every role against every permission in one table, and its editor shows the permissions of a single role or user wherever you put it β€” a section of a form, a tab, a page of its own. Each cell shows what this library resolves: in effect, implied by another permission, missing a requirement, blocked by a conflict, restricted at runtime, or withheld by a condition such as its #[RequiresMFA], with the rule named in the tooltip. Changes are written on every click or collected until the operator saves them, and every change is authorized through the gate β€” voters included.

Requirements

Package Versions
PHP 8.3 – 8.5
Laravel 12, 13

Installation

You can install the package via composer:

Usage

1. Define Permissions as Enums

Create an enum that implements PermissionDefinition:

Tip: In modular applications, consider prefixing permission values with your module name (e.g., pim-module.product.view, inventory-module.stock.update) to avoid conflicts between modules and make it clear which module owns each permission.

2. Register Permissions

Register your permission enums in a service provider:

3. Register Voters

Voters allow you to add custom authorization logic to permissions. The main advantage is that voters can be registered from any module, making them perfect for modular monolith architectures.

Using Closures

Using Voter Classes

For more complex logic, create dedicated voter classes with the #[VoterForPermission] attribute:

Register the voter class:

4. Using Authorization

The package integrates with Laravel's Gate, so you can use standard authorization methods:

Listing what a principal may do

getEffectivePermissions() returns every registered permission the principal may act on now, as a Collection of enum cases in registration order β€” ready to hand to a front end:

It asks the principal's own hasPermissionTo() for each registered permission, so rules between permissions and runtime restrictions count. Voters do not: they judge an action on a particular object, and a list has none to hand them. A permission nobody registered is not listed.

AccessControl::effectivePermissions($principal) gives the same list for any AuthControllable, including one that answers hasPermissionTo() itself.

5. Adding Permission Metadata (Optional)

Enhance your permissions with names, descriptions, and groups using PHP attributes:

Permission Groups

First, create a permission group:

Enhanced Permission Enum

Subjects

A group says which module owns a permission. A subject says what the permission is about, and there is exactly one per permission enum β€” the enum is already a stand-in for the thing being guarded.

The level matters as soon as several enums share a group. Without it, that group renders as one flat list in which View appears once per enum with nothing to tell the entries apart. Nothing has to be declared to get it: the subject is named after the enum with the Permission suffix dropped.

Label it explicitly by putting PermissionName and PermissionDescription on the enum CLASS β€” the same attributes the cases use:

A permission that declares no name of its own is labelled from its subject (View Store Settings), so annotating the class relabels every case under it at once.

Retrieving Permission Metadata

This is useful for building permission management UIs.

6. Restricting Permissions at Runtime (Optional)

Sometimes a permission has to be withheld from everybody for a while, whatever they were granted β€” a read-only mode, a maintenance window, a suspended organisation. A restriction does that without touching anybody's grants: nothing is revoked, and when the condition ends everybody holds exactly what they held before.

Declaring which permissions write data

Mark the permissions whose use writes data with #[MutatesData]. On the enum CLASS it is the default for every case; a case carrying its own REPLACES that default, so #[MutatesData(false)] opts a case out:

Read it back through the reflector:

A permission that declares nothing reads as not writing. If every permission of your application must be classified, assert declaresMutatesData() over your enums in a test β€” an enum annotated case by case would otherwise let a new, unannotated case read as "does not write" without anybody deciding so.

Registering a restriction

Register a closure in a service provider's boot(). It receives the permission being checked and returns true to withhold it. Here, a read-only mode that withholds every permission that writes:

While the closure returns true for a permission:

Several closures may be registered; a permission is restricted when any of them says so. AccessControl::isRestricted($permission) asks the same question directly.

A few things to keep in mind:

7. Rules Between Permissions (Optional)

A permission can declare how it relates to another permission. The package applies these rules itself β€” in hasPermissionTo(), and therefore in the Gate β€” and describes them to a permission-management UI.

Attribute on X Meaning
#[Requires(A)] X is effective only while A is effective.
#[ImpliedBy(A)] Whoever is granted A is granted X as well.
#[ConflictsWith(A)] X is not effective while A is effective.

Each attribute is repeatable. Several Requires on one case mean all of them are needed.

A rule changes only the permission that declares it.

How a permission is resolved for a principal:

Worth knowing:

Rules across roles: HoldsGrants

Rules are resolved over the union of a principal's grants. A requirement one role stores satisfies a permission another role stores, and a conflict between two roles is seen. For that, a role has to hand over its raw grants: declare HoldsGrants on it. HasPermissions already provides the method.

A role that declares HoldsGrants is no longer asked hasPermissionTo(): its stored grants are read as they are. If your role class overrides hasPermissionTo() β€” a super-admin role, a role that can be switched off β€” keep it off HoldsGrants, or put that logic into getGrants(). Otherwise the override stops applying, and a role that is switched off would grant again.

A role without HoldsGrants is asked hasPermissionTo() as before. It answers whether it may act, with its own rules and any restriction already applied, and that answer stands in for what it stores:

HoldsGrants also makes checks faster: a principal reads its roles' grants once, instead of scanning every role for every permission. Call forgetResolvedPermissions() after a principal's roles, or the grants of one of its roles, change within the same request.

Checking your declarations

Two mistakes throw InvalidPermissionRuleException at the first permission check:

Declarations that compile but cannot mean what they say are listed by PermissionGraph::problems(). Assert it in a test:

problems() reports:

It never reports a permission that can be allowed.

Rules in a permission-management UI

Every PermissionDto from PermissionCollection carries rules: each rule it declares or is the target of. The same PermissionRuleDto sits on both ends.

A reason is a translation key or plain text. It is passed through __() with :permission and :other (the two names), in the locale of the request that reads it. On PHP 8.5+, where an attribute argument may be a static closure, it can also be a Closure(string $permission, string $other): string.

To show why a permission is or is not effective, ask the resolver with a closure that says what is stored. The closure can describe the unsaved state of a form:

A role editor should still read and save the stored grants. See the note on grant containers in the previous section.

For many permissions over one stored state, and for an account's conditions, see PermissionResolver::explainer(); for the catalogue's own declaration problems, see PermissionGraph::problemDetails() β€” both in Conditions on Accounts.

8. Drawing Permission Graphs (Optional)

Draw the rules of the whole catalogue, or what one principal may do and why.

In the terminal

The principal is loaded with the user provider model of the default guard. Pick another guard with --guard=admin, or name the model with --model="App\Models\Admin". It has to implement AuthControllable.

For example, suppose gallery.view requires product.view, gallery.manage is implied by product.update, and both enums sit in one Products group. A user who stores product.update directly and holds an Editor role (a HoldsGrants role storing gallery.view) is drawn as:

A principal's graph shows the roles it holds (getRoles()) and its direct grants (HasPermissions). It also shows what each of them stores, and every permission that concerns the principal, marked with its state:

State Meaning
allowed effective and stored
implied effective without being stored β€” something the principal holds implies it
overridden effective because the principal's own hasPermissionTo() says so, though nothing stores or implies it β€” an administrator short-circuit
restricted the rules allow it; a runtime restriction withholds it
unmet-condition the rules allow it, the account fails a condition
missing-requirement granted (stored or implied), but a permission it requires is not active
conflict it loses a conflict it declares
denied the principal's own hasPermissionTo() refuses it for another reason
not-granted drawn only because a rule points at it

The tree prints the states with spaces (missing requirement). toArray() and the JSON output carry them as listed.

A role that implements HoldsGrants shows what it stores. Any other role is asked about each permission, and its edges read "may act". Such a role can only say whether it may act, with its own rules and any restriction already applied, so what it withholds is not drawn at all. In a read-only mode, for example, its restricted permissions disappear instead of showing as restricted. Implement HoldsGrants on your roles to get a diagram that shows everything.

In your application

Render the Mermaid text with mermaid.js on a page:

toArray() returns:

That is enough for cytoscape, d3 or a list of your own.

permission:graph --schema-version=1 still produces version 1, for a consumer built against it before conditions existed: a permission drawn as unmet-condition in version 2 is drawn as denied in version 1, the same as any other refusal the principal's own check does not explain.

Naming principals and roles

A node is labelled with:

  1. getGrantHolderName(), when the class implements DescribesGrantHolder;
  2. otherwise an Eloquent name attribute;
  3. otherwise the class name and key (Role#3).

Your own format

Implement DiagramRenderer and tag it. A renderer of an existing format replaces the package's own:

It is then available to render() and to permission:graph --format=.

9. Conditions on Accounts (Optional)

A condition withholds a permission from an account that does not meet it β€” one without multi-factor authentication, one whose e-mail is not verified β€” whatever it was granted. It is an attribute on a permission enum (it then guards every case) or on one case, and the attribute class implements Contracts\PermissionCondition. You write your own; nothing is registered, the library finds the attribute by its interface.

check() is handed the permission it guards, so one attribute can guard many permissions and still tell them apart. A condition on the enum and one on the case add up: the account must meet both. DescribesPermissionCondition is optional β€” it names the condition in a permission UI.

Who is an account

A condition applies to a principal if and only if it is Authenticatable:

Principal Conditions
A user (HasRoles / HasRolesAndPermissions) βœ“
A machine user, an API key (HasPermissions) βœ“
An account answering hasPermissionTo() itself βœ“ at the gate and in effectivePermissions(); its own hasPermissionTo() answers what it answers
A role (HasPermissions, HoldsGrants) βœ— β€” a role stores grants, it does not sign in
Anything else holding roles that does not sign in (a team) βœ—
No user at all the gate refuses it as Unauthenticated. first

Where conditions apply

Last β€” after restrictions and the rules between permissions:

Place
The gate (can(), Gate::allows(), authorize()) an unmet condition is refused with the same message as a missing permission
hasPermissionTo() of the traits false; never remembered in the per-instance memo of HasRoles
effectivePermissions() / getEffectivePermissions() left out β€” for every account, also one answering hasPermissionTo() itself

A condition withholds its own permission only. What it implies, what requires it and what it conflicts with are resolved as if the account could use it: with B #[ImpliedBy(A)] and a condition on A, an account storing A without meeting the condition has B but not A.

hasPermissionTo() called with an ability string ('order.refund') also applies the conditions of the registered permission that string names. Restrictions and the rules between permissions still do not apply to a string, as those sections say. A string naming no registered permission is answered by the grants alone, as always.

A Gate::before() callback that answers first skips the permission's gate β€” its conditions included.

Writing a condition

check() must be free of side effects and idempotent within a request, and should avoid I/O: it runs on every check β€” twice in one gate check, once in the trait and once in the gate β€” and its answer is never cached, since a cache would outlive a change in the account (MFA switched on mid-request). An exception thrown by check() reaches the caller.

The attribute class must be used in the file that declares the permission enum. PHP silently skips an attribute whose class does not exist or is not imported β€” the condition is dropped with no error or exception, and the permission is simply granted. Static analysis (PHPStan) catches the missing import; a test asserting the condition is enforced catches the rest.

Conditions in a permission UI

How Voters Work

  1. When a permission check is performed via Laravel's Gate, the package first refuses a permission withheld by a conditions) β€” conditions run after hasPermissionTo()'s own rules and before any voter is asked
  2. If the user has the permission, all registered voters for that permission are executed
  3. If any voter returns Response::deny(), the authorization fails
  4. Only if all voters return Response::allow(), the authorization succeeds

This allows different modules to add constraints to permissions without knowing about each other.

Voters vs Policies

Feature Laravel Policies Voters
Location Single class per model Can be anywhere
Modularity Coupled to model Fully decoupled
Multiple handlers No Yes
Cross-module logic Difficult Easy
Registration Automatic by convention Explicit

Model Setup

The model on which authorization checks are performed (typically User) must implement the AuthControllable interface.

This package provides three traits for managing permissions:

HasRoles (Recommended)

Use this trait when users receive permissions only through roles. This is the recommended approach for most applications.

HasPermissions

Use this trait for models that store permissions directly (e.g., a Role model). This trait provides givePermissionTo() and revokePermissionTo() methods.

Declaring HoldsGrants lets a principal resolve rules between permissions across all of its roles.

You can also use this trait directly on User.

HasRolesAndPermissions

Use this trait when users can receive permissions both through roles AND directly. Permissions are checked in both sources.

Development

Changelog

See GitHub releases for what has changed recently.

Contributing

See CONTRIBUTING for details.

Security vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). See License File for more information.



All versions of laravel-access-control with dependencies

PHP Build Version
Package Version
Requires php Version ^8.3
illuminate/support Version ^12.20 || ^13.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 happenv-com/laravel-access-control contains the following files

Loading the files please wait ...