# Queries

> controlled(), controlledFor() and uncontrolled() filter your Eloquent queries in SQL with the control of the model. A query is controlled only when it says so.

## Controlled queries

The `HasControl` trait adds three local scopes to the model:

```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
```

`controlled()` reads the signed-in user, with `Auth::user()`, when the query is built. The control adds the constraints of the perimeters that the user reaches, and of the boundary, in SQL, in one nested `where`.

**A query is controlled only when it says so.** `Post::query()->get()` reads every row: the trait registers no global scope. Add `controlled()` to every query that must be filtered.

### Guests see nothing

Without a signed-in user, `controlled()` reads no row, whatever the ability. So does `controlledFor(null)`: a missing reader never means every row. A user that no perimeter allows reads no row either: the query gets `0=1`.

## Listing another ability

Both scopes list the `view` rows by default. Pass another ability, as a name or an `Ability`, to list the rows the reader may act on:

```php
use Lomkit\Access\Ability;

Post::controlled('update')->paginate();
Post::controlledFor($user, Ability::delete())->count();
Post::controlledFor($user, 'approve')->get();
```

The list follows the policy for that ability: the perimeters that allow the reader for it, the level reached for it in each group, the boundary checked for it, and the abilities a parent delegates. A post archived under [`readOnlyWhenNotNull('archived_at')`](/essentials/boundaries#read-only-rows) stays in the `view` list and leaves the `update` list.

- A name goes through `abilityFor()`: `viewAny` lists `view`, and a business ability such as `approve` lists its rows.
- `create` throws `UnlistableAbilityException`, since the policy judges it on a draft only.
- One ability per scope: a second argument, such as `controlled('view', 'update')`, throws `IgnoredArgumentException`.

The list is what the control grants. A rule that an overridden policy method adds, or a `Gate::before()`, does not change it: keep the rules in the control, see [Policies](/essentials/policies#keep-the-rules-in-the-control).

## Named readers

`controlledFor($reader)` applies the control for a reader you name. Use it where no user is signed in, such as jobs, listeners and commands, or to act for another user:

```php
class SendDigest implements ShouldQueue
{
    public function __construct(public User $recipient) {}

    public function handle(): void
    {
        $posts = Post::controlledFor($this->recipient)->latest()->limit(10)->get();

        // ...
    }
}
```

The reader can be any Eloquent model, such as a `User` or an API client. See [Readers](/essentials/readers).

## Combining with your own conditions

The constraints of the control form one group, so a condition chained **before** `controlled()` stays an AND:

```php
Post::where('published', true)->orWhere('featured', true)->controlled()->get();
// where (published = 1 or featured = 1) and (the control)
```

A condition chained **after** `controlled()` is joined to the whole query, like any Eloquent `orWhere()`: an `orWhere()` there would bring rows from outside the control. Group your conditions in a closure:

```php
Post::controlled()->where(fn (Builder $query) => $query->where('published', true)->orWhere('featured', true))->get();
```

To narrow a list with a rule of your own, such as the posts of one author, intersect it with the controlled list: the control stays inside, so the rule can only narrow it.

```php
Post::controlledFor($user, 'update')->where(fn (Builder $query) => $query->whereBelongsTo($author, 'author'));
```

## Relations and subqueries

Relations, `whereHas()` subqueries, eager loads, lazy loads and route model binding are **not controlled** unless they say so. Each scope works on a relation or a subquery:

```php
$user->posts()->controlled()->get();

Project::whereHas('posts', fn (Builder $posts) => $posts->controlled())->get();

User::with(['posts' => fn ($posts) => $posts->controlled()])->get();

Comment::whereIn('post_id', Post::controlledFor($user, 'update')->select('id'))->get();
```

A model bound to a route is loaded without control: authorize it through its policy.

```php
public function show(Post $post)
{
    $this->authorize('view', $post);

    // ...
}
```

## Uncontrolled queries

`uncontrolled()` adds nothing: it states that a query reads every row on purpose, for statistics, seeders or a back office. It reads like `Post::query()`, and tells a reviewer that the missing control is a choice.

## Deciding the rows of a page

A page that checks `@can('update', $post)` on each row runs one query per row and ability for the perimeters checked in SQL. Decide the whole page in the query that loads it with `withAbilities()`, after `controlled()` or `controlledFor()`:

```php
$posts = Post::controlled()
    ->withAbilities(['view', 'update', 'delete'])
    ->paginate();
```

The query decides each row for each ability, and `can()`, `@can` and `authorize()` then answer without SQL. The extra columns never show in `toArray()` or the JSON. `withAbilities()` without `controlled()` or `controlledFor()` before it throws `MissingControlledReaderException`.

`controlled()` does not decide `view` by itself: list `view` in `withAbilities()` when the page checks it. [Batched decisions](/digging-deeper/batched-decisions) covers the others, `Access::preload()` and `reachableKeys()`.

## Good to know

- `controlled()` reads `Auth::user()` when it runs: do not call it from an event of the user model that the guard fires while it retrieves the user, such as `retrieved`.
- A Laravel Scout search has its own `controlled()`, `controlledFor()` and `uncontrolled()`, and must call one of them. See [Search overview](/search/overview#searching).
