Querying users and bulk assignment | laravel-permission-rust | Spatie       

 SPATIE  

laravel-permission-rust
=======================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-permission-rust](https://spatie.be/docs/laravel-permission-rust/v1)  Querying users and bulk assignment

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-permission-rust/v1) 

  Querying users and bulk assignment    
- [ Introduction ](https://spatie.be/docs/laravel-permission-rust/v1/introduction)
- [ Install and connect the application ](https://spatie.be/docs/laravel-permission-rust/v1/installation-laravel)
- [ Roles and permissions ](https://spatie.be/docs/laravel-permission-rust/v1/basic-usage)
- [ Authenticated routes and policies ](https://spatie.be/docs/laravel-permission-rust/v1/authorization)
- [ Querying users and bulk assignment ](https://spatie.be/docs/laravel-permission-rust/v1/querying-users)
- [ Console commands ](https://spatie.be/docs/laravel-permission-rust/v1/commands)
- [ Custom models and IDs ](https://spatie.be/docs/laravel-permission-rust/v1/models-and-ids)
- [ Cache and events ](https://spatie.be/docs/laravel-permission-rust/v1/cache-and-events)
- [ Integration tests ](https://spatie.be/docs/laravel-permission-rust/v1/testing)

 Querying users and bulk assignment
==================================

###  On this page 

1. [ Querying teams ](#content-querying-teams)

Querying users and bulk assignment
==============================================================================================================================================================

Scopes accept a real Laravel `Builder<Account>` and return a builder. Existing filters, ordering, limits and pagination stay on that builder. Morph identity comes from the account model's metadata, while the scope supplies the guard and team.

```
use laravel::model::model;
use spatie_permission::{PermissionRegistrar, Scope, Subject};

let registrar = PermissionRegistrar::default();
let scope = Scope { guard: "web", team: None };

let writers = registrar.query_role(
    &scope, &["writer".into()], false, Account::query(),
).await?.order_by(Account::email).limit(20).get().await?;

let editors = registrar.query_permission(
    &scope, &["edit articles".into()], false, Account::query(),
).await?.filter(Account::email.ends_with("@example.test")).get().await?;

let without_roles = registrar.query_without_roles(&scope, Account::query())?.get().await?;
let loaded = registrar.models_with_relations(&scope, Account::query()).await?;
```

Bulk assignments accept model IDs without loading each account:

```
use spatie_permission::{PermissionRegistrar, Subject};

let writer = registrar.find_role("writer", "web", None).await?;
let assignments = registrar.role(&writer).await?;
assignments.assign_to_model_ids([42, 81], "account", None).await?;
let desired = Subject::new("account", 81, "web");
assignments.sync_models(std::slice::from_ref(&desired), None).await?;
assert_eq!(assignments.models("account", None).await?.len(), 1);
assignments.remove_from_models(&[desired]).await?;
```

`query_role` and `query_permission` match any supplied role or permission. Set `without` to `true` to exclude those matches. An empty input matches nobody, or everybody when excluding. Unknown names return an error. Permission scopes include both direct and role-inherited grants; they match persisted permission identities, not arbitrary wildcard ability strings.

`models_with_relations` batch loads roles and direct permissions for the selected models. It returns each model with `roles` and `permissions` lists, using five queries regardless of the number of selected users. Role and permission model query filters still apply. Native role-permission relations remain available for further eager loading.

Bulk assignment methods accept trusted `Subject` values or explicit model IDs and a morph alias. These are administrative APIs; they do not authenticate an ID or check user existence. For interactive command-line assignment, use the [console command](commands), which loads the configured account model. Never pass unchecked HTTP input into bulk assignment.

`assign_to_models`, `remove_from_models` and `sync_models` run in real transactions and emit the same optional assignment events as individual user helpers. `sync_models(subjects, team)`replaces this role's users across morph types in the selected team only. Every desired subject must have that team and the role's guard. Other roles and teams are untouched; an empty list clears only the selected team. Validation or database failures roll back the entire operation.

Direct permissions have the same bulk API through `registrar.permission(&permission).await?`: `assign_to_model_ids`, `assign_to_models`, `remove_from_models`, `sync_models` and `models`. Sync replaces only that permission's direct assignments in the selected team. Inherited grants and other permissions are untouched.

Querying teams
--------------------------------------------------------------------------------------------------

With teams enabled, `registrar.query_team("web", [17, 29], false, Account::query())?` finds accounts with any role in either team. Set `without` to `true` to exclude them. Multiple roles in a team do not duplicate accounts; direct permissions alone do not imply team membership.

For a user's team records, pass your own native team-model builder to `user.teams(Team::query())?`and call `.get().await?`. Package code uses the model's real key; your builder retains filters, ordering and scopes. There is no package-owned default team model.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
