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

 SPATIE  

  Laravel Sluggable Go 
=======================

spatie.be/open-source

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

 Version   v1      

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

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

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

- [ Generating your first slug ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/getting-started)
- [ Using the Sluggable attribute ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/using-the-attribute)
- [ Using the HasSlug trait ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/using-the-has-slug-trait)
- [ Finding models by slug ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/finding-models-by-slug)
- [ Self-healing URLs ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/self-healing-urls)

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

- [ Combining multiple source columns ](https://spatie.be/docs/laravel-sluggable-go/v1/advanced-usage/source-fields)
- [ Tuning the uniqueness suffix ](https://spatie.be/docs/laravel-sluggable-go/v1/advanced-usage/uniqueness)
- [ Overriding the underlying actions ](https://spatie.be/docs/laravel-sluggable-go/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. [ Choosing a separator ](#content-choosing-a-separator)
7. [ Customizing the redirect ](#content-customizing-the-redirect)
8. [ Changing the URL format ](#content-changing-the-url-format)
9. [ Under the hood ](#content-under-the-hood)
10. [ When you don't need self-healing ](#content-when-you-dont-need-self-healing)

Say you publish a blog post titled "Hello World". Its URL is `/posts/hello-world`. A few days later you realise the title should have been "Hello Universe", so you update it. The slug regenerates to `hello-universe` and the URL becomes `/posts/hello-universe`. Every search engine result, every shared link, every bookmark pointing at `/posts/hello-world` now returns `404`.

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

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

Set `SelfHealing` in the model's options. Keep the create and update hooks from [Generating your first slug](getting-started).

```
func (*Post) SlugOptions() sluggable.Options[Post] {
    options := sluggable.DefaultOptions[Post]("title")
    options.SelfHealing = true
    return options
}
```

With default options, a post with id `5` and title "Hello World" exposes `hello-world-5` through `slugs.RouteKey()`.

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

Go routes use an explicit handler rather than PHP's automatic trait-based binding. Resolve the incoming key, handle a stale URL, and let Laravel handle other errors:

```
func showPost(r *web.Request) *web.Response {
    prototype := Post{}
    slugs, err := sluggable.For(r, &prototype)
    if err != nil {
        return web.Fail(err)
    }
    post, err := slugs.ResolveRoute(r, model.Query[Post](), r.PathValue("post"))
    var stale *sluggable.StaleURL
    if errors.As(err, &stale) {
        return sluggable.From(r).Redirect(r, stale)
    }
    if err != nil {
        return web.Fail(err)
    }
    return web.JSON(post)
}
```

Import `errors`, `go.laravel.com/model`, `go.laravel.com/web` and the package. Register the handler with `route.Get("/posts/{post}", showPost)`. The example uses an application-local `Post` model. Use your models package qualifier if it lives elsewhere.

Incoming pathResult`/posts/hello-world-5``200 OK` with the resolved model.`/posts/outdated-slug-5``308 Permanent Redirect` to `/posts/hello-world-5`.`/posts/hello-world-99``404 Not Found` when id `99` does not exist.`/posts/hello-world``404 Not Found` when the extracted identifier does not resolve.Use native query lookups for explicitly named columns rather than passing them through `ResolveRoute`.

The redirect uses `308` rather than `301` because `308` preserves the request method when followed. A stale `PUT`, `PATCH`, or `DELETE` still arrives at the canonical route as the same verb. Search engines treat both statuses the same for ranking. To return something else, see [Customizing the redirect](#customizing-the-redirect).

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

Pass a constrained native query to `ResolveRoute`. It adds the extracted primary key to the query you supplied. A post belonging to another author still returns `404`.

```
query := model.Query[Post]().Where("tenant_id", "=", tenantID).WhereNull("deleted_at")
post, err := slugs.ResolveRoute(ctx, query, incomingKey)
```

Relationship queries can be passed in the same way. Existing query constraints remain in place. Add your application's soft-delete filter explicitly. The package does not install PHP's global scopes or intercept scoped route binding.

For a query that should accept stale keys without redirecting, inspect `*sluggable.StaleURL` and use the model returned alongside it. Other errors must still propagate.

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

Use Laravel Go's native primary key generation on your own model:

```
type Product struct {
    ID    string  `json:"id" db:",uuid"`
    Title string  `json:"title"`
    Slug  *string `json:"slug"`
}
```

Use `db:",ulid"` for ULIDs. There are no conflicting PHP traits to combine. Generation, persistence and self-healing lookups retain the native identifier type.

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

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

Self-healing also works with translated slugs. The route key uses `Options.Locale`. `RouteKey("nl")` reads another locale without changing the model or options.

Named slug lookups use `QueryBySlug` or `FindBySlug` with the configured locale. See [Translatable slugs](../translatable-slugs).

Choosing a separator
--------------------------------------------------------------------------------------------------------------------

The default separator is `"-"`. Choose a separator that does not occur in identifiers.

```
options.SelfHealingSeparator = "--"
// route key: "hello-world--5"
```

An empty slug builds an identifier-only route key, matching PHP's build action. The default extractor requires a separator and therefore does not resolve identifier-only values. Replace both actions if empty slugs need to be routable.

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

When an incoming key is stale, `ResolveRoute` returns `*sluggable.StaleURL`. Its `Model`, `Incoming` and `Canonical` fields describe the resolved model and both keys. The default response is a `308` redirect that replaces the matching path segment and preserves the query string.

```
sluggable.New(func(config *sluggable.Config) {
    config.OnStaleURL = func(r *web.Request, stale *sluggable.StaleURL) *web.Response {
        return web.Redirect("/posts/" + url.PathEscape(stale.Canonical)).WithStatus(307)
    }
})
```

Import `net/url` for `url.PathEscape`. You can log stale access, render an old-link notification, or refuse a redirect based on request state.

Changing the URL format
-----------------------------------------------------------------------------------------------------------------------------

To use a different layout, for example `{id}--{slug}`, swap the actions that build and parse the route key. See [Putting the identifier first](../advanced-usage/overriding-actions#example-putting-the-identifier-first).

Under the hood
--------------------------------------------------------------------------------------------------

### A fresh request

When someone visits `/posts/hello-world-5`, the package splits the URL at the last separator. The right side is the primary key. It finds post `5`, confirms that the incoming key is canonical, and hands the model to your handler.

### A stale link

Rename the post to "Hello Universe" and its slug becomes `hello-universe`. The package still finds post `5` through an old key, then returns a stale-URL error. Your handler sends the `308` redirect to `/posts/hello-universe-5`.

### No database writes

The package only reads during route resolution. Your slug column is updated through model hooks when you save the model. Visiting a stale URL does not regenerate a slug or store an old one.

Because the lookup is always by primary key, changing a title never orphans an existing self-healing link.

When you don't need self-healing
------------------------------------------------------------------------------------------------------------------------------------------------------

If your slug truly never changes after creation, a native slug-column query is enough. Use `FindBySlug` or `QueryBySlug`. Be aware that any future change to the slug column breaks every existing link, which is exactly the situation self-healing exists to prevent.

 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)
