laravel-sluggable 0.2.0

Easy creation of slugs for your Laravel Rust models: a port of cviebrock/eloquent-sluggable.
Documentation

Sluggable for Laravel Rust

laravel-sluggable is a port of cviebrock/eloquent-sluggable to Laravel Rust. It generates unique slugs for your models when they are created or updated.

[!NOTE] This is a community port maintained by Rivervo. It is not an official package of Colin Viebrock. It follows cviebrock/eloquent-sluggable 13.0.2: the same settings, defaults, uniqueness rules and suffixes, with Rust naming. Slugs are made by a port of cocur/slugify 4.8.0 with its own transliteration rules, so they match the PHP package's character for character. All credit for the design goes to Colin Viebrock and the package's contributors.

Installation

cargo add laravel-sluggable

Register the service provider in src/app.rs, which adds the settings section:

use laravel_sluggable::SluggableServiceProvider;

Application::configure()
    .with_providers(|providers| {
        providers.add(SluggableServiceProvider);
    })

Making a model sluggable

Give the model a slug column, implement Sluggable and add the hooks:

use laravel::model::model;
use laravel_sluggable::{Slug, Sluggable};

#[model(hooks)]
pub struct Post {
    pub id: i64,
    pub title: String,
    pub slug: Option<String>,
}

impl Sluggable for Post {
    fn sluggable() -> Vec<Slug<Self>> {
        vec![Slug::new(Post::slug).source(Post::title)]
    }
}

laravel_sluggable::sluggable_hooks!(Post);
let post = create!(Post { title: "My Awesome Blog Post" }).await?;
// post.slug == Some("my-awesome-blog-post")

A slug column is a String or Option<String> column. Call source several times to build the slug from several columns, joined with spaces as in PHP, or use source_with for a computed source.

If your model already has Hooks, call the package from them instead of using sluggable_hooks!:

impl Hooks for Post {
    async fn creating(draft: &mut Draft<Self>) -> laravel::Result<()> {
        laravel_sluggable::creating(draft).await
    }

    async fn updating(&mut self, changes: &Changes<Self>) -> laravel::Result<()> {
        laravel_sluggable::updating(self, changes).await
    }
}

A model can have several slugs: return several Slugs.

Settings

Each Slug method is one of PHP's per-model settings. A setting the model doesn't set comes from the SluggableConfig section, PHP's config/sluggable.php, with the same defaults:

PHP setting Slug method SluggableConfig field Default
source source, source_with
maxLength max_length max_length None
maxLengthKeepWords max_length_keep_words max_length_keep_words true
method method method None (the slug engine)
separator separator separator -
unique unique unique true
uniqueSuffix unique_suffix unique_suffix None (-2, -3, …)
firstUniqueSuffix first_unique_suffix first_unique_suffix 2
reserved reserved, reserved_with reserved None
onUpdate on_update on_update false
slugEngineOptions slug_engine_options slug_engine_options cocur/slugify's defaults
Slug::new(Post::slug)
    .source(Post::title)
    .max_length(100)
    .separator("_")
    .reserved(["add", "edit"])
    .unique_suffix(|_slug, _separator, similar, _first| similar.len().to_string())

Change the defaults for every model with with_config:

Application::configure()
    .with_config(|config, _| {
        config.section_mut::<SluggableConfig>().separator = "_".to_owned();
    })

Updating models

As in PHP, a slug is generated when the model is created and the slug is empty. An update keeps the slug unless the slug is emptied or on_update(true) is set. A slug you set yourself is kept.

Custom slug engine

Override customize_slug_engine to add rules or rulesets for a slug column:

impl Sluggable for Post {
    fn sluggable() -> Vec<Slug<Self>> { /* ... */ }

    fn customize_slug_engine(engine: Slugify, _attribute: &str) -> Slugify {
        engine.add_rule("&", "and").activate_rule_set("esperanto")
    }
}

Unique slugs scoped to a query

Override with_unique_slug_constraints to limit uniqueness, for example to the same author:

fn with_unique_slug_constraints(
    query: laravel::db::Builder<Self>,
    model: &SlugSubject<'_, Self>,
    _attribute: &str,
    _config: &SlugOptions,
    _slug: &str,
) -> laravel::db::Builder<Self> {
    query.filter(Post::author_id.eq(model.get(Post::author_id).copied().flatten()))
}

find_similar_slugs (PHP's scopeFindSimilarSlugs) can be overridden the same way.

SlugService

// A unique slug without saving anything: SlugService::createSlug
let slug = SlugService::create_slug::<Post>(None, "slug", "My First Post", None).await?;
let slug = SlugService::create_slug::<Post>(None, "slug", "My First Post", Some(Slug::new(Post::slug).separator("."))).await?;

// Regenerate a saved model's slugs in memory: SlugService::slug($model, $force)
SlugService::slug(&mut post, true).await?;

Finding models by slug

Implement SluggableScopeHelpers (PHP's trait of the same name):

impl SluggableScopeHelpers for Post {}

let post = Post::find_by_slug("my-first-post").await?;
let post = Post::find_by_slug_or_fail("my-first-post").await?; // ModelNotFound, a 404 in a handler
let posts = Post::where_slug("my-first-post").get().await?;

The primary slug is the first one; override slug_key_name to pick another, as PHP's $slugKeyName.

Testing

cargo test --all-features

The tests port the PHP package's BaseTests, UniqueTests, OnUpdateTests, StaticTests and ScopeHelperTests where they map, on SQLite.

Differences from PHP

  • Settings are a Slug builder and a SluggableConfig section instead of arrays; source takes typed columns.
  • PHP hooks into the model's saving event. Here the model's Hooks call the package (sluggable_hooks! does it for you).
  • A custom uniqueSuffix closure receives the similar slugs as a list, without their model keys.
  • A reserved slug's suffix never treats the reserved list's index as the model's key (a PHP quirk).
  • strip_tags in the slug engine removes <...> tags only; PHP's strip_tags handles more edge cases.

Not yet ported (planned for a later release)

  • The slugging and slugged events (the first one can cancel slugging).
  • The saved event (sluggableEvent() returning SAVED), needed when the primary key is part of the source. With the default saving behaviour the key isn't known on create, as in PHP.
  • replicate() re-slugging the copy: use ..post.replicate().except(Post::slug) so the copy gets a new slug.
  • Soft deletes and includeTrashed: Laravel Rust has no soft deletes yet.
  • PHP sources that name a relation's attribute (author.name); use source_with with a value you have.

License

MIT. See LICENSE.md.