Generating your first slug | 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  Generating your first slug

 Version   v1      

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

  Generating your first slug    
- [ 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)

 Generating your first slug
==========================

###  On this page 

1. [ 1. Add slug options to the model ](#content-1-add-slug-options-to-the-model)
2. [ 2. Add a slug column to the migration ](#content-2-add-a-slug-column-to-the-migration)
3. [ 3. Use it ](#content-3-use-it)
4. [ 4. Wire it into a route with self-healing (optional) ](#content-4-wire-it-into-a-route-with-self-healing-optional)
5. [ What's next ](#content-whats-next)
6. [ Let the Laravel Boost skill set things up for you ](#content-let-the-laravel-boost-skill-set-things-up-for-you)

This walkthrough takes a `Post` model from nothing to a working slug in three steps: model hooks, a migration, and a query. An optional fourth step wires the slug into a route with self-healing URLs so renaming a model never breaks an old link.

1. Add slug options to the model
------------------------------------------------------------------------------------------------------------------------------------------------------

Tell the package which column to read from and which to write to. Use your own model type, not a package base model.

```
package models

import (
    "context"
    "github.com/spatie/laravel-sluggable-go"
    "go.laravel.com/db"
)

type Post struct {
    ID    int64   `json:"id"`
    Title string  `json:"title"`
    Slug  *string `json:"slug"`
}

func (*Post) SlugOptions() sluggable.Options[Post] {
    return sluggable.DefaultOptions[Post]("title")
}

func (p *Post) Creating(ctx context.Context) error {
    return sluggable.Creating(ctx, p)
}

func (p *Post) Updating(ctx context.Context, values db.Values) error {
    return sluggable.Updating(ctx, p, values)
}
```

`DefaultOptions` writes to `slug`. Change `To` to use another destination column. Column names follow Laravel Go's native `db` tags and embedded-field mappings.

2. Add a slug column to the migration
---------------------------------------------------------------------------------------------------------------------------------------------------------------------

The package writes the slug into the column you named in the options, so the table needs a matching string column.

```
func createPosts(ctx context.Context) error {
    return schema.Create(ctx, "posts", func(table *schema.Blueprint) {
        table.ID()
        table.String("title")
        table.String("slug").Nullable().Unique()
    })
}
```

Import `go.laravel.com/schema` and register the function in your application's `[]db.Migration`. The unique constraint is optional. The package appends `-1`, `-2`, etc. on collisions whether or not the database enforces uniqueness, but the constraint is a useful safety net for concurrent writers and code paths that bypass model hooks. Concurrent writers can still race, so handle a unique-constraint error and retry the write when needed.

For an existing table, add a nullable column, backfill it through model hooks, and add the unique constraint afterwards. Keep room for a uniqueness suffix beyond `MaxLength`, which limits the source before slugification.

3. Use it
---------------------------------------------------------------------------------

Slugs are written when the model is created and regenerated when the model is updated.

```
post := models.Post{Title: "Hello World"}
if err := model.Create(ctx, &post); err != nil {
    return err
}
// *post.Slug == "hello-world"

if err := model.Update(ctx, &post, db.Values{"title": "Hello Universe"}); err != nil {
    return err
}
// *post.Slug == "hello-universe"
```

Import `go.laravel.com/model`. `ctx` must carry your Laravel application, such as a request or job context. Bulk query writes do not run model hooks.

4. Wire it into a route with self-healing (optional)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Most user-editable content eventually gets renamed, and a renamed slug breaks every existing link unless you opt into self-healing URLs. With self-healing enabled the route key becomes `{slug}-{id}`, the primary key drives the lookup, and a stale slug `308`-redirects to the canonical URL instead of returning a `404`.

Set `options.SelfHealing = true` in `SlugOptions`, then use `ResolveRoute` in your handler. See [Self-healing URLs](self-healing-urls) for a complete handler, including scoped queries and redirects.

What's next
---------------------------------------------------------------------------------------

- Tune the generation rules in [Using the Sluggable attribute](using-the-attribute), which maps PHP attribute arguments to Go options.
- Look slugs up directly with [Finding models by slug](finding-models-by-slug).
- Translate slugs per locale with [Translatable slugs](../translatable-slugs).

Let the Laravel Boost skill set things up for you
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Laravel Boost's Composer discovery does not apply to Go modules. This repository includes Laravel Go's development skills and Spatie's package conventions for coding agents. See [Laravel Boost skill](../laravel-boost-skill).

 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)
