Self-healing URLs | laravel-sluggable-rust | Spatie       

 SPATIE  

  Laravel Sluggable 
====================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-sluggable-rust](https://spatie.be/docs/laravel-sluggable-rust/v1)  Basic-usage  Self-healing URLs

 Version   v1      

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

  Self-healing URLs    
- [ Introduction ](https://spatie.be/docs/laravel-sluggable-rust/v1/introduction)
- [ Requirements ](https://spatie.be/docs/laravel-sluggable-rust/v1/requirements)
- [ Support us ](https://spatie.be/docs/laravel-sluggable-rust/v1/support-us)
- [ Installation and setup ](https://spatie.be/docs/laravel-sluggable-rust/v1/installation-setup)
- [ Translatable slugs ](https://spatie.be/docs/laravel-sluggable-rust/v1/translatable-slugs)
- [ Changelog ](https://spatie.be/docs/laravel-sluggable-rust/v1/changelog)
- [ Questions and issues ](https://spatie.be/docs/laravel-sluggable-rust/v1/questions-issues)
- [ Upgrading ](https://spatie.be/docs/laravel-sluggable-rust/v1/upgrading)
- [ Testing ](https://spatie.be/docs/laravel-sluggable-rust/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-sluggable-rust/v1/releasing)

Basic usage
-----------

- [ Generating your first slug ](https://spatie.be/docs/laravel-sluggable-rust/v1/basic-usage/getting-started)
- [ Using slug options ](https://spatie.be/docs/laravel-sluggable-rust/v1/basic-usage/using-slug-options)
- [ Finding models by slug ](https://spatie.be/docs/laravel-sluggable-rust/v1/basic-usage/finding-models-by-slug)
- [ Self-healing URLs ](https://spatie.be/docs/laravel-sluggable-rust/v1/basic-usage/self-healing-urls)

Advanced usage
--------------

- [ Combining multiple source columns ](https://spatie.be/docs/laravel-sluggable-rust/v1/advanced-usage/source-fields)
- [ Tuning the uniqueness suffix ](https://spatie.be/docs/laravel-sluggable-rust/v1/advanced-usage/uniqueness)
- [ Overriding the underlying actions ](https://spatie.be/docs/laravel-sluggable-rust/v1/advanced-usage/overriding-actions)

 Self-healing URLs
=================

###  On this page 

1. [ Enabling ](#content-enabling)
2. [ Request behavior ](#content-request-behavior)
3. [ Scoped bindings and query-based lookups ](#content-scoped-bindings-and-query-based-lookups)
4. [ UUID and ULID models ](#content-uuid-and-ulid-models)
5. [ Translatable slugs ](#content-translatable-slugs)
6. [ Customizing the redirect ](#content-customizing-the-redirect)

Say you publish a blog post titled "Hello World". Its URL is `/posts/hello-world`. A few days later you change the title to "Hello Universe". The slug regenerates to `hello-universe`, and every old link now returns `404`.

Self-healing URLs fix this. The route key becomes `{slug}-{id}`. The slug can change without breaking lookups, because the primary key still resolves the model. Stale keys trigger a `308` redirect to the canonical URL.

Enabling
--------------------------------------------------------------------------------

Use the model's options to build its key, then resolve incoming composite keys explicitly in the handler:

```
use laravel::routing::Params;

async fn show(Params(key): Params<String>) -> laravel::Result<String> {
    let post = Post::slug_options()
        .resolve_route_binding(Post::query(), &key, None)
        .await?;

    match post {
        Some(post) => Ok(post.title),
        None => Err(laravel::abort(404)),
    }
}
```

Register this handler with `route.get("/posts/{key}", show)`. To generate a URL, use `format!("/posts/{}", Post::slug_options().route_key(&post, None)?)`. The default separator is `-`; `.self_healing("--")` changes it.

Request behavior
--------------------------------------------------------------------------------------------------------

Incoming pathResult`/posts/hello-world-5`The post with identifier `5`, if this is its current key.`/posts/outdated-slug-5``308 Permanent Redirect` to `/posts/hello-world-5`.`/posts/hello-world-99`No match when identifier `99` does not exist.`/posts/hello-world`No match when the final part cannot be parsed as the key type.The provider renders `StaleSelfHealingUrl` as a redirect, replacing the stale URL segment and preserving the query string. A `308` preserves the request method, including `PUT`, `PATCH`, and `DELETE`. Your route must accept that method too.

Plain identifiers also resolve. If the model has no slug, its canonical route key is the identifier alone. Visiting an old URL never writes to the database.

Scoped bindings and query-based lookups
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Pass your existing model or relationship query into `resolve_route_binding`. The package adds the identifier constraint without discarding the query's tenant, relationship, or visibility filters. Never replace an already authorized query with an unrestricted one.

This explicit resolver does not change Laravel's ordinary implicit model bindings. Named bindings such as `{post:id}` or `{post:slug}` keep their native behavior.

UUID and ULID models
--------------------------------------------------------------------------------------------------------------------

The model keeps its native Laravel key type and identifier generation. No combined identifier trait is needed. Keys only need to implement `FromStr` in addition to Laravel's `ModelKey` contract.

For UUID primary keys, use a separator that cannot occur inside the UUID, such as `--`. The default parser splits at the last separator; `-` would split inside a UUID. Keep the separator unchanged when upgrading so existing URLs remain valid.

Translatable slugs
--------------------------------------------------------------------------------------------------------------

Pass the locale to `route_key(&model, Some("nl"))` and `resolve_route_binding(query, value, Some("nl"))`. The package reads that locale without changing any model or application state.

Customizing the redirect
--------------------------------------------------------------------------------------------------------------------------------

Register an application error renderer after the package provider. Laravel tries later renderers first:

```
use laravel::{Application, http::Redirect};
use spatie_sluggable::{StaleSelfHealingUrl, service_provider};

let app = Application::configure()
    .with_providers(|providers| { providers.add(service_provider()); })
    .with_errors(|errors, _| {
        errors.render(|error: &StaleSelfHealingUrl, request, _| {
            error.redirect(request).map(|redirect: Redirect| redirect.status(307))
        });
    })
    .create();
```

The error exposes `stale` and `canonical` keys. Your renderer can log the access, reject it, or return a different response. To change the key layout itself, replace the [route-key actions](../advanced-usage/overriding-actions).

 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)
