=============== LIBRARY RULES =============== From library maintainers: - These docs cover Laravel Access Control 1.x (lomkit/laravel-access-control), which requires PHP 8.3+ and Laravel 13. Laravel 12 applications stay on 0.7, the last 0.x release. Do not write 0.x code. - Install with composer require lomkit/laravel-access-control. There is no configuration file to publish: everything is declared in the controls. - Write one control per model in app/Access/Controls (php artisan make:control PostControl) with protected string $model and perimeters(); perimeter classes go in app/Access/Perimeters (php artisan make:perimeter ClientPerimeter). - Each perimeter declares allowed() (the permission, for an Ability), query() (its rows in SQL) and should() (one row in memory), or unrestricted(). query() and should() must describe the same rows. - Group perimeters with Levels::of(), widest first: only the highest level the user reaches applies. Keep tenants apart with a boundary() on the control. - Add the HasControl trait to the model and call Access::registerPolicies() in the boot() method of a service provider. - A query is controlled only when it says so: Post::query()->controlled()->paginate(), controlled('update') for another ability, Post::controlledFor($user) in jobs and commands. A controlled query without a signed-in user returns no row. - With Laravel Scout, use the ControlledSearchable trait, give each restricting perimeter searchKeys(), and end every search with controlled() or uncontrolled(). - Run php artisan access:check in CI, and prove in tests with InteractsWithAccess (assertControlAgrees, assertLevelsNest, assertSearchAgrees) that the policy, the queries and the search agree. ### Install Laravel Boost and the skill Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/8.use-with-ai.md Run these commands to install Laravel Boost and install the skill. After updating the package, run `php artisan boost:update` so the agent reads the skill of the installed version. ```bash composer require laravel/boost --dev php artisan boost:install ``` -------------------------------- ### Install Laravel Access Control with Composer Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/1.getting-started/2.installation.md Run this Composer command to install the package. Laravel automatically discovers the service provider; no configuration file needs to be published. ```bash composer require lomkit/laravel-access-control ``` -------------------------------- ### query() callback example Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Constrains the builder and returns nothing. Throws QueryCallbackReturnedAnotherBuilderException if another builder is returned, and EmptyQueryCallbackException if no where is added. Joins throw JoinInPerimeterException. ```php ->query(function (Builder $query, User $user, Ability $ability): void { $query->where('client_id', $user->client_id); }) ``` -------------------------------- ### Create perimeter classes and control with artisan commands Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/1.getting-started/3.quick-start.md Run these artisan commands to generate three perimeter classes and one control class. The perimeter classes are placed in app/Access/Perimeters and the control in app/Access/Controls. The make:control command names the model after the control, here App\Models\Post. ```bash php artisan make:perimeter GlobalPerimeter php artisan make:perimeter ClientPerimeter php artisan make:perimeter OwnPerimeter php artisan make:control PostControl ``` -------------------------------- ### access:check output example Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/5.testing-and-tooling/2.access-check.md Example output from access:check. It lists controls, perimeters, boundaries, search engine, policy, and problems. The command exits with 1 when a problem is found, 0 otherwise. Notes never change the exit code. ```txt controls 2 built from app/Access/Controls cache ................................................................. not cached models ................................................ 2 scanned in app/Models scout driver ........................ meilisearch, from the config of this environment pivots ............ 1 BelongsToMany relation with a declared return type scanned App\Access\Controls\PostControl App\Models\Post #1.1 GlobalPerimeter ........................................ memory, unrestricted #1.2 ClientPerimeter .................................... sql, search keys client #2 SharedPerimeter .................................................... memory boundary ...................... Lomkit\Access\Boundaries\ColumnBoundary, memory, searchable search ................ ControlledSearchable on Laravel\Scout\Engines\MeilisearchEngine policy ................................................ App\Policies\PostPolicy, controlled App\Access\Controls\CommentControl App\Models\Comment #1 ThroughParent [post] ....... sql, update from the parent's update, view from the parent's view boundary ...................................................................... none search ................................................................ not searchable policy ............................. Lomkit\Access\Policies\AutomaticPolicy, automatic problems .................................................................. 1 FAILED ⇂ The [App\Access\Perimeters\SharedPerimeter] perimeter at #2 of the [App\Access\Controls\PostControl] control declares no search keys, so a reader that only this perimeter reaches finds none of its [App\Models\Post] rows in a controlled text search. Declare searchKeys() on the perimeter, or unrestricted() if it reaches every row notes ........................................................................ none ERROR 1 problem found. ``` -------------------------------- ### Define perimeters in PostControl.php Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/1.getting-started/3.quick-start.md Declares the rules for three perimeter levels in the PostControl class. The GlobalPerimeter uses unrestricted() to reach every post, ClientPerimeter filters by client_id, and OwnPerimeter filters by author_id. The Levels::of() group evaluates only the highest applicable level per ability. ```php namespace App\Access\Controls; use App\Access\Perimeters\ClientPerimeter; use App\Access\Perimeters\GlobalPerimeter; use App\Access\Perimeters\OwnPerimeter; use App\Models\Post; use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Lomkit\Access\Ability; use Lomkit\Access\Controls\Control; use Lomkit\Access\Perimeters\Levels; class PostControl extends Control { protected string $model = Post::class; protected function perimeters(): array { return [ Levels::of( GlobalPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} all posts")) ->unrestricted(), ClientPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ->should(fn (User $user, Post $post) => $post->client_id === $user->client_id) ->query(function (Builder $query, User $user): void { $query->where('client_id', $user->client_id); }), OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->should(fn (User $user, Post $post) => $post->author_id === $user->id) ->query(function (Builder $query, User $user): void { $query->where('author_id', $user->id); }), ), ]; } } ``` -------------------------------- ### Register policies with Access::registerPolicies() in AppServiceProvider Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/1.getting-started/3.quick-start.md Call Access::registerPolicies() in the boot() method of a service provider. This automatically creates policies for every controlled model that lacks its own, based on its control. ```php use Lomkit\Access\Access; public function boot(): void { Access::registerPolicies(); } ``` -------------------------------- ### Generate a control with model and perimeters Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/1.controls.md Example of using --model and repeatable --perimeters options. The command writes the control file with callbacks for each perimeter. ```bash php artisan make:control PostControl --model=Post --perimeters=GlobalPerimeter --perimeters=OwnPerimeter ``` -------------------------------- ### should() callback example Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Checks a row in memory. Optional; without it, the policy checks saved rows via query(). Required for drafts (rows about to be created). Receives the stored row after fill(). ```php ->should(fn (User $user, Post $post, Ability $ability) => $post->author_id === $user->id) ``` -------------------------------- ### Use controlled queries and policy checks Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/1.getting-started/3.quick-start.md Use the controlled() query scope to filter results by the signed-in user's permissions. Pass an action name to filter for that specific permission. Use controlledFor($user) for a named user in jobs/commands. The policy can be checked with $user->can(). Note: a query is only controlled when you explicitly call controlled(); otherwise it returns all rows. A controlled query without a signed-in user returns no rows. ```php Post::query()->controlled()->paginate(); // the posts the signed-in user may view Post::query()->controlled('update')->paginate(); // the posts the signed-in user may update Post::controlledFor($user)->get(); // for a named user, in jobs and commands $user->can('update', $post); // the policy, from the same perimeters ``` -------------------------------- ### allowed() callback example Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Checks the permission for the ability. Must return a boolean; otherwise throws PerimeterCallbackResultException. Runs at most once per reader, ability, and decision context until the next write. ```php ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ``` -------------------------------- ### PHP: Call Access::forgetDecisions() at start of each unit of work Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/2.decisions.md Use this inside a loop over tenants to clear cached decisions before processing each tenant, ensuring permission changes made by other processes are seen. A console command keeps decisions for its whole run and never sees revocations by another process unless you call forgetDecisions(). ```php foreach (Tenant::all() as $tenant) { Access::forgetDecisions(); // ... } ``` -------------------------------- ### Define a control with perimeters for a model Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/1.getting-started/1.introduction.md Create a control class for a model, defining perimeters that determine which rows users can access for each ability. The example shows a PostControl with client and own perimeters, using allowed(), query(), and optional should() methods. ```php namespace App\Access\Controls; use App\Access\Perimeters\ClientPerimeter; use App\Access\Perimeters\OwnPerimeter; use App\Models\Post; use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Lomkit\Access\Ability; use Lomkit\Access\Controls\Control; use Lomkit\Access\Perimeters\Levels; class PostControl extends Control { protected string $model = Post::class; protected function perimeters(): array { return [ Levels::of( ClientPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ->query(function (Builder $query, User $user): void { $query->where('client_id', $user->client_id); }), OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->should(fn (User $user, Post $post) => $post->author_id === $user->id) ->query(function (Builder $query, User $user): void { $query->where('author_id', $user->id); }), ), ]; } } ``` -------------------------------- ### Add HasControl trait to model (app/Models/Post.php) Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/1.getting-started/3.quick-start.md Add the HasControl trait to your Eloquent model. The package finds the corresponding control class (e.g., PostControl) in app/Access/Controls via its $model property. If the control is in another directory, use the #[ControlledBy(PostControl::class)] attribute on the model. ```php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Lomkit\Access\Controls\HasControl; class Post extends Model { use HasControl; } ``` -------------------------------- ### Controlled query scopes: controlled(), controlledFor(), uncontrolled() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/8.queries.md The HasControl trait adds three local scopes. controlled() uses Auth::user() at query build time and applies perimeter and boundary constraints in a single nested where. A query is controlled only when explicitly using these scopes; Post::query()->get() reads all rows. Without a signed-in user, controlled() and controlledFor(null) return no rows, and a user with no allowed perimeter gets 0=1. ```php Post::controlled()->paginate(); // the posts the signed-in user may view Post::controlledFor($user)->get(); // the posts a named reader may view Post::uncontrolled()->count(); // every post, on purpose ``` -------------------------------- ### Declare search token mode in service provider boot() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/6.from-the-browser.md Choose between direct engine queries with a signed token or proxied searches through a route. Declare once; a conflicting second declaration throws ConflictingSearchTokensException, while repeating the same declaration is accepted. ```php use Lomkit\Access\Access; Access::searchTokens(direct: true); // browsers query the engine with a token from Access::searchToken() Access::searchTokens(direct: false); // browsers go through a route that calls Access::guardSearch() ``` -------------------------------- ### Add GitMCP server in VS Code (.vscode/mcp.json) Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/8.use-with-ai.md Configures the GitMCP server in VS Code's MCP configuration file. ```json { "servers": { "laravel-access-control": { "type": "http", "url": "https://lomkit.gitmcp.io/laravel-access-control-doc" } } } ``` -------------------------------- ### Add GitMCP server in Cursor (.cursor/mcp.json) Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/8.use-with-ai.md Configures the GitMCP server in Cursor's MCP configuration file. ```json { "mcpServers": { "laravel-access-control": { "url": "https://lomkit.gitmcp.io/laravel-access-control-doc" } } } ``` -------------------------------- ### Ability::create() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Creates an Ability instance for the 'create' action. This is a static factory method on the Ability class. ```APIDOC ## Ability::create() ### Description Creates an Ability instance for the 'create' action. This is a static factory method on the Ability class. ### Method `Ability::create()` ### Parameters None ### Return Value - **Ability** - An immutable value object representing the 'create' ability. ### Request Example ```php use Lomkit\Access\Ability; Ability::create(); ``` ``` -------------------------------- ### Indexing and searching with Access::indexKeysOf and indexReaderKeys Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/7.your-own-client.md Use this snippet to index rows of one model and search with reader keys. It shows how to upsert documents with '_access' and '_boundary' keys, then filter search hits by those keys. The $index variable represents your engine client; declare '_access' and '_boundary' as arrays of strings for filtering. ```php use Lomkit\Access\Access; // Indexing: the rows of one model at a time $posts = Post::query()->whereKey($ids)->get(); foreach (Access::indexKeysOf($posts) as $id => $keys) { foreach ($chunks[$id] as $chunk) { $index->upsert([...$chunk, '_access' => $keys['_access'], '_boundary' => $keys['_boundary']]); } } // Searching $keys = Access::indexReaderKeys($request->user(), Post::class); if ($keys->isClosed()) { return []; } $hits = $index->search($query, filters: [ ['_access', 'in', $keys->values()['_access']], ['_boundary', 'in', $keys->values()['_boundary']], ]); ``` -------------------------------- ### Ability::restore() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Creates an Ability instance for the 'restore' action. This is a static factory method on the Ability class. ```APIDOC ## Ability::restore() ### Description Creates an Ability instance for the 'restore' action. This is a static factory method on the Ability class. ### Method `Ability::restore()` ### Parameters None ### Return Value - **Ability** - An immutable value object representing the 'restore' ability. ### Request Example ```php use Lomkit\Access\Ability; Ability::restore(); ``` ``` -------------------------------- ### Ability::view() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Creates an Ability instance for the 'view' action. This is a static factory method on the Ability class. ```APIDOC ## Ability::view() ### Description Creates an Ability instance for the 'view' action. This is a static factory method on the Ability class. ### Method `Ability::view()` ### Parameters None ### Return Value - **Ability** - An immutable value object representing the 'view' ability. ### Request Example ```php use Lomkit\Access\Ability; Ability::view(); ``` ``` -------------------------------- ### Access::preload() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/3.batched-decisions.md Preloads ability decisions for already-loaded rows in one query per ability and model, keeping answers for the request. ```APIDOC ## Access::preload() ### Description Preloads ability decisions for already-loaded rows in one query per ability and model, keeping answers for the request. ### Method Static method ### Endpoint `Access::preload($reader, $ability, $rows)` ### Parameters #### Arguments - **$reader** (mixed) - Required - The reader (user) for whom decisions are preloaded. - **$ability** (string|Ability) - Required - Ability name or `Ability` object. - **$rows** (iterable) - Required - Collection of model instances (can belong to multiple controlled models). ### Usage ```php use Lomkit\Access\Ability; use Lomkit\Access\Access; Access::preload($user, 'update', $posts); Access::preload($user, Ability::delete(), $posts); ``` ### Notes - Runs one query per ability and per model, in chunks of 1,000 keys. - Unsaved rows are skipped (refused as `unsaved` without SQL). - If reader has no key or is not saved, no query is run. ``` -------------------------------- ### Sync index settings and import documents Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/2.engines.md Pushes the configured index settings to the search engine and imports the Post model documents. Run these commands after updating the engine-specific configuration. ```bash php artisan scout:sync-index-settings php artisan scout:import "App\Models\Post" ``` -------------------------------- ### MultiSearchTypesenseEngine subclass for Typesense multi_search Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/2.engines.md Use when readers hold more keys than the ~100 allowed by a GET query string (Typesense rejects >4,000 encoded characters with HTTP 400). Requires Scout 11.7 or later. The subclass passes the access filter to the engine, so it is trusted without Access::trustSearchEngine(). ```php use Laravel\Scout\Builder; use Laravel\Scout\EngineManager; use Laravel\Scout\Engines\TypesenseEngine; use Typesense\Client; use Typesense\Documents; class MultiSearchTypesenseEngine extends TypesenseEngine { protected function executeSearch(Builder $builder, Documents $documents, array $options): mixed { $results = $this->typesense->getMultiSearch()->perform([ 'searches' => [[...$options, 'collection' => $builder->index ?? $builder->model->searchableAs()]], ]); $result = $results['results'][0] ?? []; if (isset($result['error'])) { throw $this->marshalMultiSearchException($result); } return $result; } } // In the boot() method of a service provider resolve(EngineManager::class)->extend('typesense', fn () => new MultiSearchTypesenseEngine( new Client(config('scout.typesense.client-settings')), config('scout.typesense.max_total_results', 1000), config('scout.typesense'), )); ``` -------------------------------- ### PostControl grantingPerimeter using applicablePerimeters Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/4.row-checks.md Inside a control, the protected applicablePerimeters($reader, $ability) lists perimeters that apply to a reader for an ability. This example iterates over them and returns the first perimeter that admits the reader for the update ability and the given post. It reads the kept perimeters of the reader, so it agrees with the policy and the queries; it does not check the boundary against a row (the policy does). applicablePerimeters() is final, so give added methods distinctive names. ```php use Illuminate\Database\Eloquent\Model; use Lomkit\Access\Ability; use Lomkit\Access\Perimeters\Perimeter; class PostControl extends Control { public function grantingPerimeter(Model $reader, Post $post): ?Perimeter { foreach ($this->applicablePerimeters($reader, Ability::update()) as $perimeter) { if ($perimeter->admits($reader, Ability::update(), $post)) { return $perimeter; } } return null; } } ``` -------------------------------- ### Ability::of('approve') Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Creates an Ability instance for a custom business ability by name. This is a static factory method on the Ability class. ```APIDOC ## Ability::of('approve') ### Description Creates an Ability instance for a custom business ability by name. This is a static factory method on the Ability class. ### Method `Ability::of(string $name)` ### Parameters - **name** (string) - Required - The name of the business ability. ### Return Value - **Ability** - An immutable value object representing the given ability. ### Request Example ```php use Lomkit\Access\Ability; Ability::of('approve'); ``` ``` -------------------------------- ### Access::preload() for loaded rows Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/3.batched-decisions.md Preloads ability decisions for already-loaded rows. Runs one query per ability and per model, in chunks of 1,000 keys. Unsaved rows are skipped; a reader without a key or not saved runs no query. ```php use Lomkit\Access\Ability; use Lomkit\Access\Access; Access::preload($user, 'update', $posts); Access::preload($user, Ability::delete(), $posts); ``` -------------------------------- ### Ability::update() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Creates an Ability instance for the 'update' action. This is a static factory method on the Ability class. ```APIDOC ## Ability::update() ### Description Creates an Ability instance for the 'update' action. This is a static factory method on the Ability class. ### Method `Ability::update()` ### Parameters None ### Return Value - **Ability** - An immutable value object representing the 'update' ability. ### Request Example ```php use Lomkit\Access\Ability; Ability::update(); ``` ``` -------------------------------- ### Ability::delete() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Creates an Ability instance for the 'delete' action. This is a static factory method on the Ability class. ```APIDOC ## Ability::delete() ### Description Creates an Ability instance for the 'delete' action. This is a static factory method on the Ability class. ### Method `Ability::delete()` ### Parameters None ### Return Value - **Ability** - An immutable value object representing the 'delete' ability. ### Request Example ```php use Lomkit\Access\Ability; Ability::delete(); ``` ``` -------------------------------- ### Cache and clear access controls with access:cache and access:clear Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/5.testing-and-tooling/3.cache-and-about.md Run access:cache to write control and watch cache files into bootstrap/cache, and access:clear to remove them. The cache is used as-is, so run it again in every deployment after adding, moving, or deleting a control or adding a reindexWhen(). optimize runs access:cache, optimize:clear runs access:clear. ```bash php artisan access:cache php artisan access:clear ``` -------------------------------- ### $ability->name() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Returns the name of the ability as a string. This is an instance method on the Ability class. ```APIDOC ## $ability->name() ### Description Returns the name of the ability as a string. This is an instance method on the Ability class. ### Method `$ability->name()` ### Parameters None ### Return Value - **string** - The name of the ability. ### Request Example ```php use Lomkit\Access\Ability; $ability = Ability::view(); $ability->name(); // 'view' ``` ``` -------------------------------- ### $ability->is('view') Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Compares the ability by name with a string or another Ability instance. This is an instance method on the Ability class. ```APIDOC ## $ability->is('view') ### Description Compares the ability by name with a string or another Ability instance. This is an instance method on the Ability class. ### Method `$ability->is(string|Ability $ability)` ### Parameters - **ability** (string|Ability) - Required - The ability name or Ability instance to compare against. ### Return Value - **bool** - True if the ability names match, false otherwise. ### Request Example ```php use Lomkit\Access\Ability; $ability = Ability::view(); $ability->is('view'); ``` ``` -------------------------------- ### Use the control for policies, queries, and searches Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/1.getting-started/1.introduction.md After defining a control, the same rules apply everywhere: policy checks, controlled queries, and Scout searches. The search requires search keys on perimeters and the ControlledSearchable trait on the model. ```php $user->can('update', $post); // the policy Post::query()->controlled()->paginate(); // the posts the signed-in user may view Post::controlled('update')->count(); // the posts they may update Post::search('budget')->controlled()->get(); // a Laravel Scout search, with the same rules ``` -------------------------------- ### Listing another ability with controlled() and controlledFor() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/8.queries.md Both scopes list 'view' rows by default. Pass another ability as a name or an Ability to list rows the reader may act on. The list follows the policy for that ability, including perimeters, levels, boundaries, and delegated abilities. 'create' throws UnlistableAbilityException, and a second ability argument throws IgnoredArgumentException. ```php use Lomkit\Access\Ability; Post::controlled('update')->paginate(); Post::controlledFor($user, Ability::delete())->count(); Post::controlledFor($user, 'approve')->get(); ``` -------------------------------- ### Perform controlled search with pagination Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/1.overview.md Runs a controlled search for 'budget' with pagination, returning 25 results per page. The search is a single engine query filtered by the reader's keys. ```php Post::search('budget')->controlled()->paginate(25); ``` -------------------------------- ### Define perimeters with search keys in PostControl Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/1.overview.md Defines perimeters with allowed callbacks, query filters, and search keys for client and author levels. The search keys name 'client' and 'author' map row and reader values to document and reader keys. ```php protected function perimeters(): array { return [ Levels::of( GlobalPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} all posts")) ->unrestricted(), ClientPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ->query(fn (Builder $query, User $user) => $query->where('client_id', $user->client_id)) ->searchKeys( name: 'client', row: fn (Post $post) => $post->client_id, reader: fn (User $user) => $user->client_id, ), OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->query(fn (Builder $query, User $user) => $query->where('author_id', $user->id)) ->searchKeys( name: 'author', row: fn (Post $post) => $post->author_id, reader: fn (User $user) => $user->id, ), ), ]; } ``` -------------------------------- ### Add GitMCP server in Claude Code Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/8.use-with-ai.md Adds the GitMCP server for the Laravel Access Control docs to Claude Code using the HTTP transport. ```bash claude mcp add --transport http laravel-access-control https://lomkit.gitmcp.io/laravel-access-control-doc ``` -------------------------------- ### Access::indexKeysOf() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/7.your-own-client.md Returns the access keys to store on documents for each row of a model. Use it when indexing rows into your own search engine. ```APIDOC ## Access::indexKeysOf() ### Description Returns an array keyed by row ID, each value containing `_access` and `_boundary` arrays of digest strings to store on the corresponding search document. ### Method `Access::indexKeysOf($rows)` ### Parameters - **$rows** (iterable) - Required - Collection or iterable of saved model rows of one model. ### Return Value - **array** - Keyed by row key (int or string), each value is `['_access' => string[], '_boundary' => string[]]`. ### Exceptions - `InvalidIndexRowException` - If rows contain multiple models, non-model values, unsaved/deleted/soft-deleted rows, or invalid keys. ### Notes - Loads `load` relations once for all rows. - String keys that are decimal integers are cast to int. ``` -------------------------------- ### Ability string interpolation Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Ability objects can be interpolated into strings, producing the ability name followed by a space and the given string. This is a magic method on the Ability class. ```APIDOC ## Ability string interpolation ### Description Ability objects can be interpolated into strings, producing the ability name followed by a space and the given string. This is a magic method on the Ability class. ### Method `__toString()` ### Parameters None ### Return Value - **string** - The ability name. ### Request Example ```php use Lomkit\Access\Ability; $ability = Ability::view(); "{$ability} posts"; // 'view posts' ``` ``` -------------------------------- ### Run access:check with Scout driver Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/5.testing-and-tooling/2.access-check.md Run the artisan command in CI with the production Scout driver. The engine checks use the driver of the environment the command runs in. ```bash SCOUT_DRIVER=meilisearch php artisan access:check ``` -------------------------------- ### TenantBoundary searchKeys() method Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/1.overview.md Declares search keys for a boundary using SearchKeys::of() with name, row, and reader callbacks. The reader may also accept AccessContext as a second parameter. A controlled search on an engine that stores documents throws UnsearchableBoundaryException if the boundary lacks searchKeys(). A reader with a null boundary value finds nothing. ```php use Illuminate\Database\Eloquent\Model; use Lomkit\Access\Search\SearchKeys; class TenantBoundary extends Boundary { protected function searchKeys(): ?SearchKeys { return SearchKeys::of( name: 'tenant', row: fn (Model $row) => $row->tenant_id, reader: fn (User $user) => $user->tenant_id, ); } // scope() and includes() as on the Boundaries page } ``` -------------------------------- ### reachableKeys() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/3.batched-decisions.md Returns the keys of rows a reader may act on, in one query, in the order of the provided rows. ```APIDOC ## reachableKeys() ### Description Returns the keys of rows a reader may act on, in one query, in the order of the provided rows. ### Method Static method ### Endpoint `Access::controlFor(Post::class)->reachableKeys($reader, $ability, $rows)` ### Parameters #### Arguments - **$reader** (mixed) - Required - The reader (user) for whom keys are retrieved. - **$ability** (string|Ability) - Required - Ability name or `Ability` object. - **$rows** (iterable) - Required - Collection of model instances. ### Usage ```php use Lomkit\Access\Ability; use Lomkit\Access\Access; $editable = Access::controlFor(Post::class)->reachableKeys($user, Ability::update(), $posts); ``` ### Notes - Returns keys in the order of `$rows`. - Useful for filtering already-loaded rows, such as search results. ``` -------------------------------- ### Ability::forceDelete() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Creates an Ability instance for the 'forceDelete' action. This is a static factory method on the Ability class. ```APIDOC ## Ability::forceDelete() ### Description Creates an Ability instance for the 'forceDelete' action. This is a static factory method on the Ability class. ### Method `Ability::forceDelete()` ### Parameters None ### Return Value - **Ability** - An immutable value object representing the 'forceDelete' ability. ### Request Example ```php use Lomkit\Access\Ability; Ability::forceDelete(); ``` ``` -------------------------------- ### Generate perimeter and control classes with artisan commands Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/5.testing-and-tooling/4.generators.md Scaffold perimeter and control classes. Use --hooks for perimeter hooks, --model and --perimeters for control model and perimeters, --parent for belongsTo relations. ```bash php artisan make:perimeter ClientPerimeter php artisan make:perimeter EditorialPerimeter --hooks php artisan make:control PostControl --model=Post --perimeters=ClientPerimeter --perimeters=EditorialPerimeter php artisan make:control CommentControl --parent=post ``` -------------------------------- ### routes/web.php: Register search route with auth middleware Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/6.from-the-browser.md Route that points to SearchController and requires authentication. The front end's search client and InstantSearch adapter should use this URL instead of the engine's. ```php Route::post('/search', SearchController::class)->middleware('auth'); ``` -------------------------------- ### makeSearchableUsing() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/1.overview.md Override this method to include access keys in the searchable data. Must return $this->withAccessKeys($models) or the documents will not be found by controlled searches. ```APIDOC ### Description Override this method to include access keys in the searchable data. Must return `$this->withAccessKeys($models)` or the documents will not be found by controlled searches. ### Method makeSearchableUsing ### Parameters - **$models** (Collection) - Required - The collection of models to be made searchable. ### Return Value - **Collection** - The collection with access keys added. ### Request Example ```php public function makeSearchableUsing(Collection $models): Collection { return $this->withAccessKeys($models->load('tags')); } ``` ``` -------------------------------- ### Show Access Control section with php artisan about --only=access_control Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/5.testing-and-tooling/3.cache-and-about.md Prints the Access Control section of php artisan about. The output shows rows like Version, Controls, Discovery paths, Cache, Automatic policies, Scout, and laravel-rest-api. The section never makes about fail; empty values print 'none' and unreadable rows print 'unavailable:' with the first line of the error. ```bash php artisan about --only=access_control ``` ```txt Access Control ................................................................ Automatic policies ................................................. registered Cache .............................................................. not cached Controls ................................................................... 12 Discovery paths .................................................. app/Access/Controls Scout ...................................................... installed, meilisearch driver Version ........................................................................ 1.0.0 laravel-rest-api ............................... installed, AccessControlExtension enabled ``` -------------------------------- ### ClientPerimeter::new()->query() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/2.perimeters.md Defines the query callback for a perimeter. This is a method on the ClientPerimeter class (or its parent) that sets the callback used to apply query constraints. ```APIDOC ## ClientPerimeter::new()->query() ### Description Defines the query callback for a perimeter. This is a method on the ClientPerimeter class (or its parent) that sets the callback used to apply query constraints. ### Method `query(callable $callback)` ### Parameters - **callback** (callable) - Required - A callback that receives the query builder, the user, and the ability and returns void. ### Return Value - **Perimeter** - The perimeter instance for chaining. ### Request Example ```php ClientPerimeter::new() ->query(function (Builder $query, User $user, Ability $ability): void { $query->where('client_id', $user->client_id); if (! $ability->is('view')) { $query->where('author_id', $user->id); } }); ``` ``` -------------------------------- ### reachableKeys() for loaded rows Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/3.batched-decisions.md Returns in one query the keys of rows the reader may act on, in the order of $rows. Use it to filter already-loaded rows, such as search results. ```php use Lomkit\Access\Ability; use Lomkit\Access\Access; $editable = Access::controlFor(Post::class)->reachableKeys($user, Ability::update(), $posts); ``` -------------------------------- ### Publish stubs with artisan stub:publish Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/5.testing-and-tooling/4.generators.md Publishes the stubs used by make:control and make:perimeter so you can customize generated code. Use --force after upgrades to overwrite your copies. ```bash php artisan stub:publish ``` -------------------------------- ### Declare search keys with searchKeys Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/1.overview.md Define a perimeter's search keys with name, row, and reader callbacks. The name must be unique and valid; invalid names throw InvalidSearchKeyNameException, duplicates throw DuplicateSearchKeyNameException. Row and reader return values, lists, or tuples; null gives no key. ```php ->searchKeys( name: 'client', row: fn (Post $post) => $post->client_id, reader: fn (User $user) => $user->client_id, ) ``` -------------------------------- ### Authorize create with draft model Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/7.policies.md Pass the draft model to authorize('create') to check where the new row will land. The draft must be inside the boundary and a perimeter; only in-memory checks apply since the draft is not saved yet. ```php $draft = new Post($request->validated()); $this->authorize('create', [Post::class, $draft]); $draft->save(); ``` -------------------------------- ### searchKeys() Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/1.overview.md Declares the search keys for a perimeter. Must be called at the end of a perimeter chain. Defines how row keys and reader keys are computed. ```APIDOC ### Description Declares the search keys for a perimeter. Must be called at the end of a perimeter chain. Defines how row keys and reader keys are computed. ### Method searchKeys ### Parameters - **name** (string) - Required - Lowercase letters, digits and underscores, unique in the control. Invalid names throw `InvalidSearchKeyNameException`, duplicates throw `DuplicateSearchKeyNameException`. - **row** (callable) - Required - Callback that returns the keys of a row when indexed. Can return a value, list of values, or list of tuples. Values must be int, string, or backed enum; otherwise throws `InvalidSearchKeyValueException`. `null` gives no key. - **reader** (callable) - Required - Callback that returns the keys of a reader at each search. Can accept an `AccessContext` as second parameter. Invalid signatures throw `InvalidSearchKeyReaderException`. - **load** (array) - Optional - Relations to eager load for the row callback. Relations not declared here throw `UndeclaredSearchKeyRelationException`. ### Request Example ```php ->searchKeys( name: 'client', row: fn (Post $post) => $post->client_id, reader: fn (User $user) => $user->client_id, ) ``` ### Request Example (with relations) ```php ->searchKeys( name: 'shared', row: fn (Post $post) => $post->sharedWith->modelKeys(), reader: fn (User $user) => $user->id, load: ['sharedWith:id'], ) ``` ### Request Example (with decision context) ```php use Lomkit\Access\AccessContext; ->searchKeys( name: 'author', row: fn (Post $post) => [[$post->brand_id, $post->author_id]], reader: fn (User $user, AccessContext $context) => [[$context->decisionContext()['brand'], $user->id]], ) ``` ``` -------------------------------- ### Search keys with exception on specific rows Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/4.exceptions-and-dates.md Defines a perimeter where each row lists the readers who see it, and the reader has one key. Includes reindexing rules for stand-ins and exclusions; until the job runs, the stand-in still finds the excluded post. ```php StandInPerimeter::new() // allowed() and query() with the exclusions, as in SQL ->searchKeys( name: 'stand_in', row: fn (Post $post) => $post->author->standIns ->reject(fn (StandIn $standIn) => $standIn->excludes($post)) ->pluck('stand_in_id') ->all(), reader: fn (User $user) => $user->id, load: ['author.standIns.exclusions'], ) ->reindexWhen(StandIn::class, changed: ['principal_id', 'stand_in_id'], rows: fn (StandIn $standIn) => Post::where('author_id', $standIn->principal_id)) ->reindexWhen(StandInExclusion::class, changed: ['post_id'], rows: fn (StandInExclusion $exclusion) => Post::whereKey($exclusion->post_id)), ``` -------------------------------- ### Search keys with exception on a dimension (sector) Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/4.exceptions-and-dates.md Defines a perimeter that grants keys per sector, computing the reader's keys as the complement of their exclusions. Keys are computed at each search, so nothing is reindexed when an exclusion changes. ```php StandInPerimeter::new() // allowed() and query() with the exclusions, as in SQL ->searchKeys( name: 'stand_in', row: fn (Post $post) => [[$post->author_id, $post->sector_id]], reader: fn (User $user) => $user->standingInFor->flatMap( fn (StandIn $standIn) => array_map(fn (int $sector): array => [$standIn->principal_id, $sector], $standIn->allowedSectorIds()), )->all(), ), ``` -------------------------------- ### withAbilities() with controlledFor() for paging editable rows Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/6.digging-deeper/3.batched-decisions.md Pages through rows a reader may act on by listing them with controlledFor($user, 'update'), then deciding other abilities on the same rows. The reader is fixed by controlledFor(). ```php $editable = Post::controlledFor($user, 'update') ->withAbilities(['view', 'delete']) ->paginate(); ``` -------------------------------- ### Set decision context resolver in service provider boot method Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/9.readers.md Declare the decision context values once in the boot() method of a service provider. The resolver must return an array of strings, ints, booleans or nulls keyed by name; anything else throws InvalidDecisionContextException. Without a resolver, the context is empty. ```php use Lomkit\Access\Access; public function boot(): void { Access::decisionContextUsing(fn (): array => ['team' => Team::current()?->id]); } ``` -------------------------------- ### Trust a custom search engine with Access::trustSearchEngine Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/2.engines.md Call Access::trustSearchEngine in the boot() method of a service provider to allow an engine that correctly filters controlled searches. Any other engine throws UnsupportedSearchEngineException. A trusted engine must implement specific filtering and metadata behaviors. ```php Access::trustSearchEngine(ElasticsearchEngine::class); ``` -------------------------------- ### Publish access-control language files Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/7.policies.md Publishes the translation files for refusal messages so they can be customized. After publishing, edit lang/vendor/access-control/{locale}/refusals.php. ```bash php artisan vendor:publish --tag=access-control-lang ``` -------------------------------- ### LoanPerimeter with date-dependent reader keys Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/4.exceptions-and-dates.md Defines a perimeter that grants abilities for vehicles currently on loan to the user. The same date condition appears in query() and reader, and now() is compared from PHP to avoid clock mismatches. ```php LoanPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} borrowed vehicles")) ->query(fn (Builder $query, User $user) => $query->whereHas('loans', fn (Builder $loans) => $loans ->whereBelongsTo($user) ->where('starts_at', '<=', now()) ->where(fn (Builder $end) => $end->whereNull('ends_at')->orWhere('ends_at', '>=', now())))) ->searchKeys( name: 'loan', row: fn (Vehicle $vehicle) => $vehicle->getKey(), reader: fn (User $user) => Loan::query() ->whereBelongsTo($user) ->where('starts_at', '<=', now()) ->where(fn (Builder $end) => $end->whereNull('ends_at')->orWhere('ends_at', '>=', now())) ->pluck('vehicle_id') ->all(), ), ``` -------------------------------- ### Define boundary method in policy Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/2.essentials/7.policies.md Defines the boundary method that returns a Boundary instance. It scopes rows by the user's current workspace and makes locked posts read-only for all abilities except view. ```php protected function boundary(): Boundary { return Boundary::where('workspace_id', fn (User $user) => $user->current_workspace_id) ->readOnlyWhenNotNull('locked_at'); } ``` -------------------------------- ### Use AccessContext in reader callback Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/1.overview.md The reader callback can accept AccessContext as its second parameter to read decision context, such as brand. The ability is always view. A second parameter that cannot receive AccessContext or a third parameter without default throws InvalidSearchKeyReaderException. ```php use Lomkit\Access\AccessContext; ->searchKeys( name: 'author', row: fn (Post $post) => [[$post->brand_id, $post->author_id]], reader: fn (User $user, AccessContext $context) => [[$context->decisionContext()['brand'], $user->id]], ) ``` -------------------------------- ### Search with controlled, controlledFor, uncontrolled, and plain search Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/1.overview.md Shows the four search variants on a ControlledSearchable model. A search without controlled(), controlledFor(), or uncontrolled() throws UndeclaredSearchScopeException; declaring two of them throws ConflictingSearchScopeException. controlled() and controlledFor() take no ability; passing one throws UnsearchableAbilityException. ```php Post::search('budget')->controlled()->paginate(25); // the posts the signed-in user may view Post::search('budget')->controlledFor($user)->get(); // for a named reader: jobs, listeners, commands Post::search('budget')->uncontrolled()->paginate(25); // every post, on purpose: back office, exports Post::search('budget')->paginate(25); // throws UndeclaredSearchScopeException ``` -------------------------------- ### Make Post model controlled and searchable Source: https://github.com/lomkit/laravel-access-control-doc/blob/main/content/1.x/3.search/1.overview.md Adds the HasControl and ControlledSearchable traits to the Post model to enable controlled search behavior. ```php use Lomkit\Access\Controls\HasControl; use Lomkit\Access\Search\ControlledSearchable; class Post extends Model { use HasControl, ControlledSearchable; } ```