Essentials

Parents

ThroughParent gives a child row the access of its parent, such as a comment that whoever may view its post may view, through the control of the parent.

A child with the access of its parent

A child row often has the access of its parent: a comment is visible to whoever may view its post. Declare it with ThroughParent in the control of the child:

app/Access/Controls/CommentControl.php
use Lomkit\Access\Perimeters\ThroughParent;

class CommentControl extends Control
{
    protected string $model = Comment::class;

    protected function perimeters(): array
    {
        return [
            ThroughParent::belongsTo('post', inverse: 'comments'),
        ];
    }
}
  • belongsTo() names the belongsTo relation from the child to its parent.
  • The control of the parent decides, for the same reader: its perimeters, its levels and its boundary. The child's own boundary still applies to the child.
  • It works in the policy, in controlled(), in the row checks and in the batched decisions. A row check is one exists query through whereHas(), with the global scopes of the parent.
  • inverse names the hasMany from the parent to its children. The search needs it to reindex the children when the parent changes, so a searchable child requires it. Elsewhere it is optional, and checked when given.

php artisan make:control CommentControl --parent=post writes the entry.

Never write the parent by hand, as a query() with whereHas('post', ...): that callback runs without the control of the parent unless it calls controlledFor() itself, and opens every comment of every post once that call is forgotten.

Delegated abilities

Only view is delegated by default. Reusing every ability would let whoever may update a post delete any comment on it. delegates() replaces the default with the abilities it lists:

ThroughParent::belongsTo('post')->delegates(['view', 'update', 'create' => 'view']);
  • A list item delegates the same ability: update on the comment asks for update on the post.
  • A string key maps an ability of the child to an ability of the parent: creating a comment asks for view on the post.
  • For an ability it does not delegate, the perimeter does not apply.

Compare the abilities one by one: delegating delete to the parent's update lets every editor of a post delete its comments.

A permission of the child (AND)

A child is often reachable when the reader holds a permission of the child itself and reaches the parent. Declare that permission with allowed() on the ThroughParent:

ThroughParent::belongsTo('post', inverse: 'comments')
    ->delegates(['view', 'create' => 'view'])
    ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} comments"));
  • An ability that the perimeter does not delegate is refused first, without calling allowed().
  • When allowed() returns false, the parent is not touched: no query.
  • Otherwise the parent decides.

allowed() receives the ability of the child, create above, not the parent's view. It can only narrow what the parent grants.

Other rows (OR)

A perimeter next to the ThroughParent grants other rows, such as the comments the reader wrote, whatever the post:

protected function perimeters(): array
{
    return [
        ThroughParent::belongsTo('post', inverse: 'comments'),
        AuthorPerimeter::new()
            ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own comments"))
            ->query(fn (Builder $query, User $user) => $query->where('author_id', $user->id)),
    ];
}

ThroughParent takes no other callback: should(), query(), searchKeys(), reindexWhen(), unrestricted() and ThroughParent::new() throw ThroughParentCallbackException. So:

You needWrite
A permission of the reader, on top of the parentallowed() on the ThroughParent
A condition on the child rowthe boundary of the child
Other rowsa perimeter next to the ThroughParent

A ThroughParent adds up like any loose perimeter, so two parents add up too, and it can be a level of a Levels::of() group. Parents nest: the post can itself inherit from its project.

The parent's control, not its policy

The control of the parent decides; the parent's policy is never called. A rule that the parent's policy adds on top of its control, such as an update allowed on drafts only, is not inherited, and delegating that ability would grant more than the Gate does on the parent.

Move such a rule into the control of the parent, usually its boundary: Boundary::where(...)->readOnlyWhenNotNull('closed_at'), or a boundary class whose scope() and includes() refuse the abilities other than view on such rows. The parent's own lists become right too. assertControlAgrees() on the parent fails while its policy adds a rule.

Drafts

A comment about to be created is not in the database. With create delegated, the draft loads its parent by the foreign key, in one query, and the control of the parent decides on that stored parent:

$draft = new Comment(['post_id' => $post->id, 'body' => $body]);

$user->can('create', [Comment::class, $draft]); // asks the post's control, for the mapped ability

A draft without a parent key, or whose parent does not exist, is refused. A relation loaded on the draft is ignored: only the foreign key counts.

Decisions without a row

viewAny, and create without a draft, have no row to check. A ThroughParent counts for them only when it delegates the ability, its own allowed() accepts, and the reader reaches at least one perimeter of the parent for the mapped ability.

A reader who holds the permission of the child but reaches nothing on the parent, and no other perimeter of the child, gets a 403 no_perimeter on viewAny, not an empty list. A reader who reaches the parent without rows there gets an empty list. Where the child must be listable, grant the parent ability too.

Errors

The control checks its ThroughParent perimeters when it builds its perimeters, before any query:

MistakeException
The relation does not exist, or is not a belongsToInvalidParentRelationException
inverse is not the hasMany of the parent on the same keysInvalidParentRelationException
The parent model has no controlMissingParentControlException
The parents lead back to the childParentCycleException
delegates() gets an empty list, an ability twice, or something else than an abilityInvalidDelegationException
The relation method runs a query while it builds the relationRelationInspectionQueryException
A second allowed()DuplicatePerimeterCallbackException

Parents of several types

ThroughParent follows a belongsTo relation. A child readable through any of several parents, such as a note linked to contracts and customers by a note_links table, takes a perimeter checked in SQL that reaches each type of parent through its control:

LinkedSubjectsPerimeter::new()
    ->allowed(fn (User $user, Ability $ability): bool => $ability->is('view') && $user->can('view notes'))
    ->query(function (Builder $query, User $user): void {
        $query->whereHas('links', fn (Builder $links) => $links->whereHasMorph(
            'subject',
            [Contract::class, Customer::class],
            fn (Builder $subjects) => $subjects->controlledFor($user),
        ));
    }),

A note is readable when the reader may view at least one of its subjects, each decided by its own control. Keep each part of this recipe:

  • $ability->is('view') in allowed(): controlledFor($user) checks each parent for view, whatever the ability decided on the note, so without it every reader of a parent may update and delete the note.
  • controlledFor($user) with the reader that the callback receives, and nothing else in that closure: never controlled(), which reads the signed-in user.
  • The listed types, never '*': with '*', the types come from the link table, and any controlled type that a row names would open the note.
  • No should(): the policy and the lists then decide with this same query.
  • A permission of the child in allowed(): without a row, viewAny is granted to every reader whom allowed() accepts, whether they reach a parent or not, where a ThroughParent asks the control of the parent.

The perimeter declares no search keys, grants no draft and checks no cycle. Keep such a model out of the search engine, or search it with Scout's database driver.