SeaORM Sluggable
Unique, readable URL slugs for SeaORM entities, generated on save: any language transliterated, unique per table or scope, reserved words, custom suffixes.
Describe the slug once, and every insert gets one: "Rust for PHP developers" becomes
rust-for-php-developers, the next one rust-for-php-developers-1. Works with any SeaORM
app, including Loco.
Features
- Automatic: one trait and one line in the save hook, no manual slug code
- Unique:
title,title-1,title-2, optionally only within a scope (per category, per tenant) - Any language: every script is transliterated to ASCII; official national rules per feature (Ukrainian today), or your own
- Safe for URLs: slugs stay stable on update by default, and reserved words (
new,edit) never become slugs - Flexible: several source columns, separator, length, custom suffixes, conditional skipping
- Tested against a real database, every documentation example compiled
Installation
cargo add sea-orm-sluggable
Quick start
Describe the slug:
use sea_orm_sluggable::{SlugConfig, Sluggable};
impl Sluggable for posts::ActiveModel {
fn slug_config() -> SlugConfig<Self> {
SlugConfig::new([posts::Column::Title], posts::Column::Slug)
}
}
Fill it in the save hook:
#[async_trait::async_trait]
impl ActiveModelBehavior for posts::ActiveModel {
async fn before_save<C: ConnectionTrait>(self, db: &C, insert: bool) -> Result<Self, DbErr> {
Ok(sea_orm_sluggable::fill_slug(self, db, insert).await?)
}
}
That's it:
let post = posts::ActiveModel {
title: Set("Hello, World!".to_string()),
..Default::default()
}
.insert(&db)
.await?;
assert_eq!(post.slug, "hello-world");
Options
SlugConfig::new([posts::Column::Title], posts::Column::Slug)
.on_update(true) // default: off, changing a slug breaks old links
.prevent_overwrite(true) // keep a slug an editor typed in
.scope(|post: &posts::ActiveModel| {
Condition::all().add(posts::Column::CategoryId.eq(post.category_id.clone().unwrap()))
})
.options(
SlugOptions::default()
.separator("_")
.max_length(100)
.reserved(["new", "edit", "feed"]),
)