Check if a user is authorized to perform a given action

1.0.1 2024-12-23 00:08 UTC

This package is auto-updated.

Last update: 2024-12-23 00:13:33 UTC


README

Latest Stable Version Total Downloads Daily Downloads Monthly Downloads Latest Unstable Version License composer.lock

Check if a user is authorized to perform a given action.

License

Licensed under MIT. Totally free for private or commercial projects.

Installation

composer require andrewdyer/gate

Getting Started

To get started with the Gate library, you need to create an instance of the Gate class and pass an Authenticatable user to it.

use Anddye\Gate\Gate;
use Anddye\Gate\Authenticatable;

class User implements Authenticatable {
    // User implementation
}

$user = new User();
$gate = new Gate($user);

Usage

Defining Abilities

You can define abilities using the define method. The first argument is the name of the ability, and the second argument is a callback that determines if the user has the ability.

$gate->define('edit-post', function ($user, $post) {
    return $user->id === $post->user_id;
});

Checking Abilities

You can check abilities using the allows and denies methods.

if ($gate->allows('edit-post', $post)) {
    // The user can edit the post
}

if ($gate->denies('edit-post', $post)) {
    // The user cannot edit the post
}

Authorizing Actions

You can authorize actions using the authorize method. This method will throw an UnauthorizedException if the user does not have the required abilities.

try {
    $gate->authorize(['edit-post'], $post);
    // The user is authorized to edit the post
} catch (UnauthorizedException $e) {
    // The user is not authorized to edit the post
}

Registering Before Callbacks

You can register a callback to run before all checks using the before method.

$gate->before(function ($user, $ability) {
    if ($user->isAdmin()) {
        return true;
    }
});