Custom models and IDs | 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)  Custom models and IDs

 Version   v1      

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

  Custom models and IDs    
- [ 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)

 Custom models and IDs
=====================

Custom models and IDs
=======================================================================================================================

`PermissionRegistrar` uses the supplied integer-keyed `Role` and `Permission` models. Use `Registrar<AppRole>` to select application-owned models. The role model names its permission model through `RoleModel::Permission`. Both use the same key type, which may be `i64`, Laravel's `Uuid` or `Ulid`, or `String`. UUIDs and ULIDs are generated by the native ORM. String-keyed factories must supply their own keys.

This example uses UUIDs and different model, table and pivot names. These are native `#[model]`structs, with native typed columns and many-to-many relations:

```
use laravel::{db::Builder, model::{model, create, BelongsToMany, Column, ManyToMany}, str::Uuid};
use spatie_permission::{GrantModel, PermissionModel, RoleModel, Registrar};

#[model(table = "app_permissions")]
pub struct AppPermission {
    pub id: Uuid,
    pub name: String,
    pub guard_name: String,
    #[belongs_to_many(table = "app_role_permissions", foreign_join_key = "permission_id", related_join_key = "role_id")]
    pub roles: BelongsToMany<AppRole>,
}

#[model(table = "app_roles")]
pub struct AppRole {
    pub id: Uuid,
    pub name: String,
    pub guard_name: String,
    pub team_id: String,
    #[belongs_to_many(table = "app_role_permissions", foreign_join_key = "role_id", related_join_key = "permission_id")]
    pub permissions: BelongsToMany<AppPermission>,
}

impl GrantModel for AppPermission {
    const NAME: Column<Self, String> = Self::name;
    const GUARD: Column<Self, String> = Self::guard_name;
    fn query() -> Builder<Self> { Self::query() }
}
impl PermissionModel for AppPermission {
    const MODEL_PERMISSIONS: &'static str = "app_model_permissions";
    async fn create_permission(name: &str, guard: &str) -> laravel::Result<Self> {
        create!(AppPermission { name, guard_name: guard }).await
    }
}
impl GrantModel for AppRole {
    const NAME: Column<Self, String> = Self::name;
    const GUARD: Column<Self, String> = Self::guard_name;
    fn query() -> Builder<Self> { Self::query() }
}
impl RoleModel for AppRole {
    type Permission = AppPermission;
    const TEAM: Column<Self, String> = Self::team_id;
    const MODEL_ROLES: &'static str = "app_model_roles";
    const ROLE_PERMISSIONS: &'static str = "app_role_permissions";
    async fn create_role(name: &str, guard: &str, team: &str) -> laravel::Result<Self> {
        create!(AppRole { name, guard_name: guard, team_id: team }).await
    }
    fn permission_relation(&self) -> ManyToMany<Self, AppPermission> { self.permissions() }
}

async fn migration(tx: &mut laravel::db::AnyTransaction<'_>) -> laravel::Result<()> {
    spatie_permission::migrate_for::<AppRole>(tx).await
}

let registrar = Registrar::<AppRole>::default();
let role = registrar.create_role("writer", "web", None).await?;
let permission = registrar.create_permission("edit articles", "web").await?;
registrar.role(&role).await?.give_permission_to(permission.identifier()).await?;
```

Install `service_provider::<Account, AppRole>()` and use `PermissionMiddleware<Account, AppRole>` on routes. Policies resolve that same `Registrar<AppRole>` type. Give each database/model set its own cache key when sharing a store.

`GrantModel::NAME`, `GUARD` and `RoleModel::TEAM` may point to differently named string columns. The primary key and table name come from native model metadata, including `#[key]` and `#[column("...")]`. Pivot table names come from the model traits. Override these `RoleModel`constants to select pivot columns:

- `ROLE_PIVOT_KEY`, default `role_id`.
- `PERMISSION_PIVOT_KEY`, default `permission_id`.
- `MODEL_MORPH_KEY`, default `model_id`.
- `TEAM_FOREIGN_KEY`, default `team_id`.

Keep native relation attributes consistent with those names. Migrations, queries, bulk helpers, cleanup and events all use the same selection. Models and pivots must use the application's default connection for atomic transactions.

Add extra columns or timestamps through `GrantModel::additional_columns(&mut Blueprint)`. For example, call `table.timestamps()` for native timestamp fields. The model's create methods set application defaults using the real `create!` macro. A filtered `GrantModel::query()` applies an application scope to package lookups, lists and authorization; it does not change what a raw SQL query or direct native relation returns. The integration tests exercise renamed columns, extra fields, timestamps and scoped permission models for both UUID and ULID keys.

Role/permission deletion is a hard delete with foreign-key cascades. The framework does not provide ORM soft deletes. The provider listens to native `Deleted<Account>` events and removes that account's polymorphic assignments in the deletion's transaction. Query deletes or muted model events skip lifecycle listeners; call `delete_model_assignments` explicitly for those paths.

 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)
