PHPackages                             tetthys/cake - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. tetthys/cake

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

tetthys/cake
============

Functional &amp; Layered Authorization for Laravel — Declarative, Composable, Testable

0.3.4(5mo ago)254MITPHPPHP &gt;=8.3

Since Sep 17Pushed 5mo agoCompare

[ Source](https://github.com/tetthys/cake)[ Packagist](https://packagist.org/packages/tetthys/cake)[ RSS](/packages/tetthys-cake/feed)WikiDiscussions dev Synced today

READMEChangelog (10)Dependencies (2)Versions (20)Used By (0)

Tetthys/Cake
============

[](#tetthyscake)

> Functional &amp; Layered Authorization for Laravel — Declarative, Composable, Testable

---

⚙️ Installation
---------------

[](#️-installation)

```
composer require tetthys/cake
```

Laravel auto-discovers the service provider:

```
"extra": {
  "laravel": {
    "providers": [
      "Tetthys\\Cake\\Integration\\Laravel\\CakeServiceProvider"
    ]
  }
}
```

Once installed, Cake automatically registers:

- `@cakeCan` / `@cakeCannot` Blade directives
- `cake` middleware
- global helper `cakeCan()`

---

🚀 Quick Usage
-------------

[](#-quick-usage)

### 🧩 1. Define Rules

[](#-1-define-rules)

```
// app/Policies/PostRules.php
namespace App\Policies;

use Illuminate\Http\Request;
use Tetthys\Cake\Rule\{Rule, RuleSet, Pred, Combinators as C};

final class PostRules
{
    public function update(Request $request): RuleSet
    {
        $post = $request->route('post');

        return new RuleSet([
            new Rule(
                'OwnerOrAdmin_WhenDraft',
                C::S_or(
                    Pred::S(fn($u) => $u->id === $post->user_id),
                    Pred::S(fn($u) => in_array('admin', $u->roles, true))
                ),
                Pred::D(fn($u, $a, $o, $c) => $o->data->status === 'draft')
            ),
        ]);
    }
}
```

> - **S** → Subject condition (who)
> - **D** → Domain condition (when/what)
> - A `RuleSet` is a list of `(S ∧ D)` rules. If any matches → **Permit**, otherwise → **Deny (by default)**

---

### 🧱 2. Controller Integration

[](#-2-controller-integration)

Use the built-in trait `AuthorizesRequest`.

```
use Tetthys\Cake\Integration\Laravel\AuthorizesRequest;
use App\Policies\PostRules;

class PostController
{
    use AuthorizesRequest;

    public function update(Request $request, Post $post)
    {
        $decision = $this->authorizeWithCake(
            $request,
            'post.update',
            $post,
            app(PostRules::class)->update($request)
        );

        // Decision implements isPermit() / isDeny()
        return response()->json(['ok' => $decision->isPermit()]);
    }
}
```

---

### 🪶 3. Blade Directives

[](#-3-blade-directives)

```
@cakeCan('post.update', $post)
  ✏️ Edit
@else
  You cannot edit this post.
@endcakeCan

@cakeCannot('post.update', $post)
  ❌ No permission
@endcakeCannot
```

✅ Automatically infers `App\Policies\PostRules@update` from action name + object type. You can also pass:

- Explicit `"App\\Policies\\PostRules@update"` string, or
- A pre-built `RuleSet` instance.

---

### ⚡ 4. Middleware (Route-Level)

[](#-4-middleware-route-level)

You can authorize before the controller executes.

```
// explicit
Route::put('/posts/{post}', [PostController::class, 'update'])
    ->middleware('cake:post.update,App\\Policies\\PostRules@update');
```

or just use the shorthand — automatic inference:

```
// automatic inference -> App\Policies\PostRules@update
Route::put('/posts/{post}', [PostController::class, 'update'])
    ->middleware('cake:post.update');
```

> Cake finds your route model (`{post}`), infers `"App\Policies\PostRules@update"`, and denies (403) if no rule matches.

---

### 🧩 5. Helper Function

[](#-5-helper-function)

```
use function Tetthys\Cake\Integration\Laravel\cakeCan;

if (cakeCan('post.update', $post)) {
    // Do something only if permitted
}
```

This helper can take:

- action string (`'post.update'`)
- model or object
- optional `RuleSet` or `"Class@method"` string

If omitted, Cake will infer the policy automatically.

---

### 🧪 6. Testing

[](#-6-testing)

```
use Tetthys\Cake\Engine\Engine;
use Tetthys\Cake\Model\{Actor, Action, ObjectRef, Context};
use App\Policies\PostRules;

$engine = app(Engine::class);

$decision = $engine->decide(
    new Actor('u-1', ['user']),
    new Action('post.update'),
    new ObjectRef('Post', (object)['user_id' => 'u-1', 'status' => 'draft']),
    new Context(),
    app(PostRules::class)->update(request())
);

expect($decision->isPermit())->toBeTrue();
```

Because rules are **pure functions**, you can test them without HTTP or Laravel context.

---

🧠 Key Features
--------------

[](#-key-features)

FeatureDescription**Declarative**Express access as composable predicates, not `if` trees**Composable**Combine `S` and `D` with AND / OR / NOT**Secure**Deny-by-default — no implicit permits**Laravel-Ready**Works in controllers, Blade, middleware, and helpers**Functional**Stateless and testable, rule logic is pure PHP---

🧾 License
---------

[](#-license)

MIT © Tetthys

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance70

Regular maintenance activity

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Recently: every ~12 days

Total

19

Last Release

171d ago

PHP version history (2 changes)0.0.1PHP &gt;=8.1

0.1.1PHP &gt;=8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/115064626?v=4)[tetthys](/maintainers/tetthys)[@tetthys](https://github.com/tetthys)

---

Top Contributors

[![tetthys](https://avatars.githubusercontent.com/u/115064626?v=4)](https://github.com/tetthys "tetthys (32 commits)")

---

Tags

laravelauthorizationrbacfunctionalaccess-controlabacPolicy

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/tetthys-cake/health.svg)

```
[![Health](https://phpackages.com/badges/tetthys-cake/health.svg)](https://phpackages.com/packages/tetthys-cake)
```

###  Alternatives

[casbin/casbin

a powerful and efficient open-source access control library for php projects.

1.3k1.5M54](/packages/casbin-casbin)[casbin/laravel-authz

An authorization library that supports access control models like ACL, RBAC, ABAC in Laravel.

331368.6k4](/packages/casbin-laravel-authz)[casbin/webman-permission

webman casbin permission plugin

533.5k2](/packages/casbin-webman-permission)[casbin/codeigniter-permission

Associate users with roles and permissions, use Casbin in CodeIgniter4 Web Framework.

463.1k](/packages/casbin-codeigniter-permission)[hosseinhezami/laravel-permission-manager

Advanced permission manager for Laravel.

383.3k](/packages/hosseinhezami-laravel-permission-manager)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
