Policy class abstract

Base class for organizing authorization policies.

Policies group related authorization logic together, making it easier to manage permissions for specific models or features.

Creating a Policy

class PostPolicy extends Policy {
  @override
  void register() {
    Gate.define('view-post', view);
    Gate.define('update-post', update);
    Gate.define('delete-post', delete);
  }

  bool view(Model user, Post post) {
    return post.isPublished || user.id == post.userId;
  }

  bool update(Model user, Post post) {
    return user.id == post.userId;
  }

  bool delete(Model user, Post post) {
    return user.isAdmin || user.id == post.userId;
  }
}

Registering Policies

In your GateServiceProvider.boot():

PostPolicy().register();
CommentPolicy().register();

Constructors

Policy()

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
register() → void
Register the policy's abilities with the Gate.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited